mirror of
https://github.com/Such-Software/wownerogue.git
synced 2026-12-04 12:54:08 +01:00
feat: add tavern render kit and character entitlements
This commit is contained in:
@@ -471,3 +471,11 @@ BLOCK_SOURCE=daemon
|
||||
# GAME_MODE=
|
||||
|
||||
CRYPTO_TYPE=WOW
|
||||
|
||||
# =============================================================================
|
||||
# Tavern & Multiplayer modes (optional)
|
||||
# =============================================================================
|
||||
# Tavern: a walkable social room (chat, avatars, spectator camera).
|
||||
TAVERN_ENABLED=false
|
||||
# Server-tick / snapshot broadcast cadence in ms (default 100 = 10 Hz)
|
||||
# TAVERN_TICK_MS=100
|
||||
|
||||
@@ -87,6 +87,12 @@ const DEFAULT_CONFIG = Object.freeze({
|
||||
happyHour: null
|
||||
}
|
||||
},
|
||||
products: {
|
||||
// Standalone products that do not grant a game entry. Example:
|
||||
// { id: 'pack_3d', label: '3D Character Pack', price: 500000000000n,
|
||||
// grants: { packs: ['kenney-3d-characters'] } }
|
||||
cosmetic: []
|
||||
},
|
||||
limits: {
|
||||
maxGamesPerHour: 60,
|
||||
maxPayoutsPerDay: 100,
|
||||
@@ -211,6 +217,31 @@ function safeParseJson(value, fallback) {
|
||||
}
|
||||
}
|
||||
|
||||
function cloneGrantPayload(grants) {
|
||||
if (!grants || typeof grants !== 'object') return undefined;
|
||||
return cloneConfig(grants);
|
||||
}
|
||||
|
||||
function normalizeConfiguredProduct(product, fallback = {}) {
|
||||
if (!product || typeof product !== 'object') return null;
|
||||
const id = product.id || fallback.id;
|
||||
if (!id) return null;
|
||||
const out = {
|
||||
id,
|
||||
label: product.label || fallback.label || id,
|
||||
price: parseAtomicValue(product.price, fallback.price || 0n)
|
||||
};
|
||||
if (product.credits != null || fallback.credits != null) {
|
||||
out.credits = parseInteger(product.credits, fallback.credits || 0);
|
||||
}
|
||||
if (product.bonus != null || fallback.bonus != null) {
|
||||
out.bonus = parseInteger(product.bonus || 0, fallback.bonus || 0);
|
||||
}
|
||||
const grants = cloneGrantPayload(product.grants || fallback.grants);
|
||||
if (grants) out.grants = grants;
|
||||
return out;
|
||||
}
|
||||
|
||||
class PaymentConfigManager {
|
||||
constructor(options = {}) {
|
||||
this.logger = options.logger || console;
|
||||
@@ -274,12 +305,11 @@ class PaymentConfigManager {
|
||||
|
||||
const packageJson = safeParseJson(process.env.CREDITS_PACKAGES, null);
|
||||
if (Array.isArray(packageJson) && packageJson.length > 0) {
|
||||
config.modes.credits.packages = packageJson.map(pkg => ({
|
||||
id: pkg.id,
|
||||
credits: parseInteger(pkg.credits, 0),
|
||||
price: parseAtomicValue(pkg.price, 0n),
|
||||
bonus: parseInteger(pkg.bonus || 0, 0)
|
||||
})).filter(pkg => pkg.id);
|
||||
config.modes.credits.packages = packageJson.map(pkg => normalizeConfiguredProduct(pkg, {
|
||||
credits: 0,
|
||||
bonus: 0,
|
||||
price: 0n
|
||||
})).filter(pkg => pkg && pkg.id);
|
||||
} else if (process.env.CREDITS_PACKAGE_PRICE) {
|
||||
const overridePrice = parseAtomicValue(process.env.CREDITS_PACKAGE_PRICE, null);
|
||||
if (overridePrice !== null) {
|
||||
@@ -289,6 +319,13 @@ class PaymentConfigManager {
|
||||
}
|
||||
}
|
||||
|
||||
const cosmeticProducts = safeParseJson(process.env.COSMETIC_PRODUCTS, null);
|
||||
if (Array.isArray(cosmeticProducts)) {
|
||||
config.products.cosmetic = cosmeticProducts
|
||||
.map(product => normalizeConfiguredProduct(product, { price: 0n }))
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
config.payouts.enabled = parseBoolean(process.env.PAYOUTS_ENABLED, config.payouts.enabled);
|
||||
config.payouts.rules.direct.enabled = parseBoolean(process.env.DIRECT_PAYOUTS_ENABLED, config.payouts.rules.direct.enabled);
|
||||
config.payouts.rules.direct.multipliers.escape = parseFloatValue(process.env.DIRECT_PAYOUT_ESCAPE, config.payouts.rules.direct.multipliers.escape);
|
||||
@@ -385,6 +422,14 @@ class PaymentConfigManager {
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const product of this.config.products.cosmetic || []) {
|
||||
if (!product.id) {
|
||||
throw new Error('Each cosmetic product requires an id');
|
||||
}
|
||||
if (product.price <= 0n) {
|
||||
throw new Error(`Cosmetic product ${product.id} has invalid price`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async updateConfig(updates) {
|
||||
|
||||
+174
-32
@@ -16,6 +16,8 @@ const {
|
||||
const { ValidationError, normalizeError } = require('../utils/errors');
|
||||
const paymentConfig = require('../config/paymentConfig');
|
||||
const money = require('../money/atomic');
|
||||
const Entitlements = require('../multiplayer/entitlements');
|
||||
const ProductGrants = require('../payments/productGrants');
|
||||
|
||||
// A wallet "not enough (unlocked) money" error is raised BEFORE the tx is broadcast, so it
|
||||
// is SAFE to retry (no double-pay risk) — unlike an ambiguous post-broadcast failure. Monero
|
||||
@@ -263,6 +265,17 @@ class GameModeManager {
|
||||
};
|
||||
}
|
||||
|
||||
getCosmeticProducts() {
|
||||
const products = this.configSnapshot?.products?.cosmetic;
|
||||
return Array.isArray(products) ? products : [];
|
||||
}
|
||||
|
||||
getCosmeticProduct(productId) {
|
||||
const products = this.getCosmeticProducts();
|
||||
if (!productId) return products[0] || null;
|
||||
return products.find(p => p.id === productId) || null;
|
||||
}
|
||||
|
||||
calculatePayout(mode, { treasureFound = false } = {}) {
|
||||
const normalizedMode = (mode || this.gameMode || 'FREE').toUpperCase();
|
||||
const usingCredits = normalizedMode === 'PAID_CREDITS';
|
||||
@@ -292,12 +305,14 @@ class GameModeManager {
|
||||
* @param {object} packageInfo - Package info (credits, bonus, etc.)
|
||||
* @returns {object} Result with success, creditsAdded, newBalance, alreadyProcessed
|
||||
*/
|
||||
async processCreditsPackageConfirmation(socketId, paymentId, packageInfo = null, receivedAmount = null) {
|
||||
async processProductPaymentConfirmation(socketId, paymentId, productInfo = null, receivedAmount = null) {
|
||||
try {
|
||||
// Look up user from payment record's user_id (stable across socket reconnects)
|
||||
// This avoids the bug where socket ID changes if user refreshes during confirmation
|
||||
const paymentLookup = await this.db.query(`
|
||||
SELECT user_id, description, status FROM payments WHERE id = $1
|
||||
SELECT user_id, description, status, payment_type, product_id, product_grants
|
||||
FROM payments
|
||||
WHERE id = $1
|
||||
`, [paymentId]);
|
||||
|
||||
if (paymentLookup.rows.length === 0) {
|
||||
@@ -312,18 +327,29 @@ class GameModeManager {
|
||||
}
|
||||
|
||||
const userId = paymentLookup.rows[0].user_id;
|
||||
const paymentRow = paymentLookup.rows[0];
|
||||
|
||||
// Determine credits to add from package info or payment description
|
||||
let creditsToAdd = 10; // Default fallback
|
||||
if (packageInfo && packageInfo.credits) {
|
||||
creditsToAdd = Number(packageInfo.credits) + (Number(packageInfo.bonus) || 0);
|
||||
const paymentType = paymentRow.payment_type || 'credits_package';
|
||||
let fallbackCredits = paymentType === 'credits_package' ? 10 : 0;
|
||||
if (productInfo && productInfo.credits) {
|
||||
fallbackCredits = Number(productInfo.credits) + (Number(productInfo.bonus) || 0);
|
||||
} else {
|
||||
const desc = paymentLookup.rows[0].description || '';
|
||||
const match = desc.match(/(\d+)\s*credits?/i);
|
||||
if (match) {
|
||||
creditsToAdd = parseInt(match[1], 10) || 10;
|
||||
fallbackCredits = parseInt(match[1], 10) || fallbackCredits;
|
||||
}
|
||||
}
|
||||
const durableProduct = {
|
||||
id: paymentRow.product_id,
|
||||
grants: paymentRow.product_grants || undefined
|
||||
};
|
||||
const product = productInfo || durableProduct;
|
||||
const productGrants = ProductGrants.normalizeProductGrants(product, { credits: fallbackCredits });
|
||||
const creditsToAdd = productGrants.credits;
|
||||
const productId = product?.id || paymentRow.product_id || paymentType;
|
||||
const grantJson = ProductGrants.serializeProductGrants(productGrants);
|
||||
|
||||
// CRITICAL: Wrap all three operations in a transaction.
|
||||
// If any step fails, the payment stays 'pending' and can be recovered.
|
||||
@@ -334,35 +360,71 @@ class GameModeManager {
|
||||
SET status = 'confirmed',
|
||||
credits_purchased = $1,
|
||||
confirmed_at = NOW(),
|
||||
received_amount = COALESCE($3, received_amount)
|
||||
received_amount = COALESCE($3, received_amount),
|
||||
product_id = COALESCE(product_id, $4),
|
||||
product_grants = $5::jsonb
|
||||
WHERE id = $2 AND status = 'pending'
|
||||
RETURNING id
|
||||
`, [creditsToAdd, paymentId, receivedAmount]);
|
||||
`, [creditsToAdd, paymentId, receivedAmount, productId, JSON.stringify(grantJson)]);
|
||||
|
||||
if (paymentUpdateResult.rows.length === 0) {
|
||||
// Already processed by another instance - not an error
|
||||
return { alreadyProcessed: true };
|
||||
}
|
||||
|
||||
// Step 2: Add credits to user (using payment's user_id, not socket lookup)
|
||||
// Step 2: Add credits / premium tier to user (using payment's user_id, not socket lookup)
|
||||
const updateResult = await client.query(`
|
||||
UPDATE users
|
||||
SET credits = credits + $1,
|
||||
total_credits_purchased = COALESCE(total_credits_purchased, 0) + $1,
|
||||
premium_level = CASE
|
||||
WHEN $3::text IS NULL THEN premium_level
|
||||
ELSE $3::text
|
||||
END,
|
||||
updated_at = NOW()
|
||||
WHERE id = $2
|
||||
RETURNING credits
|
||||
`, [creditsToAdd, userId]);
|
||||
RETURNING id, credits, total_credits_purchased, premium_level
|
||||
`, [creditsToAdd, userId, productGrants.premiumLevel]);
|
||||
|
||||
const newBalance = updateResult.rows[0]?.credits ?? creditsToAdd;
|
||||
const totalCreditsPurchased = updateResult.rows[0]?.total_credits_purchased ?? creditsToAdd;
|
||||
const premiumLevel = updateResult.rows[0]?.premium_level || 'free';
|
||||
|
||||
// Step 3: Record credit transaction for audit trail
|
||||
await client.query(`
|
||||
INSERT INTO credit_transactions (user_id, amount, reason, balance_after, transaction_type)
|
||||
VALUES ($1, $2, 'package_purchase', $3, 'purchase')
|
||||
`, [userId, creditsToAdd, newBalance]);
|
||||
// Step 3: Record credit transaction for audit trail when credits were granted.
|
||||
if (creditsToAdd > 0) {
|
||||
await client.query(`
|
||||
INSERT INTO credit_transactions (user_id, amount, reason, balance_after, transaction_type)
|
||||
VALUES ($1, $2, 'package_purchase', $3, 'purchase')
|
||||
`, [userId, creditsToAdd, newBalance]);
|
||||
}
|
||||
|
||||
return { newBalance };
|
||||
// Step 4: Grant cosmetic/render packs. Idempotent so retrying a confirmed
|
||||
// product cannot duplicate entitlements.
|
||||
for (const pack of productGrants.packs) {
|
||||
await client.query(`
|
||||
INSERT INTO user_pack_entitlements (user_id, pack_id, source, expires_at, metadata)
|
||||
VALUES ($1, $2, $3, $4, $5::jsonb)
|
||||
ON CONFLICT (user_id, pack_id) DO UPDATE
|
||||
SET source = EXCLUDED.source,
|
||||
expires_at = EXCLUDED.expires_at,
|
||||
metadata = user_pack_entitlements.metadata || EXCLUDED.metadata
|
||||
`, [
|
||||
userId,
|
||||
pack.id,
|
||||
pack.source || 'product_purchase',
|
||||
pack.expiresAt || null,
|
||||
JSON.stringify({ productId, paymentId })
|
||||
]);
|
||||
}
|
||||
|
||||
const grantRows = await client.query(`
|
||||
SELECT pack_id
|
||||
FROM user_pack_entitlements
|
||||
WHERE user_id = $1
|
||||
AND (expires_at IS NULL OR expires_at > NOW())
|
||||
`, [userId]);
|
||||
|
||||
return { newBalance, totalCreditsPurchased, premiumLevel, packGrants: grantRows.rows || [] };
|
||||
});
|
||||
|
||||
if (result.alreadyProcessed) {
|
||||
@@ -370,16 +432,26 @@ class GameModeManager {
|
||||
return { success: false, alreadyProcessed: true, reason: 'Payment already processed' };
|
||||
}
|
||||
|
||||
console.log(`Credits package confirmed: +${creditsToAdd} credits for user ${userId}, new balance: ${result.newBalance}`);
|
||||
const entitlements = Entitlements.snapshotForUser({
|
||||
id: userId,
|
||||
credits: result.newBalance,
|
||||
total_credits_purchased: result.totalCreditsPurchased,
|
||||
premium_level: result.premiumLevel
|
||||
}, result.packGrants);
|
||||
|
||||
console.log(`Product payment confirmed: ${productId} (+${creditsToAdd} credits) for user ${userId}, new balance: ${result.newBalance}`);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
creditsAdded: creditsToAdd,
|
||||
newBalance: result.newBalance
|
||||
newBalance: result.newBalance,
|
||||
totalCreditsPurchased: result.totalCreditsPurchased,
|
||||
grantsApplied: grantJson,
|
||||
entitlements
|
||||
};
|
||||
} catch (error) {
|
||||
const normalized = normalizeError(error, 'Failed to process credits package confirmation');
|
||||
console.error('Error processing credits package:', normalized.message);
|
||||
const normalized = normalizeError(error, 'Failed to process product payment confirmation');
|
||||
console.error('Error processing product payment:', normalized.message);
|
||||
return {
|
||||
success: false,
|
||||
reason: normalized.safeMessage
|
||||
@@ -387,18 +459,23 @@ class GameModeManager {
|
||||
}
|
||||
}
|
||||
|
||||
async _findReusablePayment(userId, paymentType) {
|
||||
async processCreditsPackageConfirmation(socketId, paymentId, packageInfo = null, receivedAmount = null) {
|
||||
return this.processProductPaymentConfirmation(socketId, paymentId, packageInfo, receivedAmount);
|
||||
}
|
||||
|
||||
async _findReusablePayment(userId, paymentType, productId = null) {
|
||||
if (!userId) return null;
|
||||
const result = await this.db.query(`
|
||||
SELECT id, subaddress, expected_amount, payment_type, status, created_at, expires_at, description
|
||||
SELECT id, subaddress, expected_amount, payment_type, status, created_at, expires_at, description, product_id, product_grants
|
||||
FROM payments
|
||||
WHERE user_id = $1
|
||||
AND payment_type = $2
|
||||
AND ($3::text IS NULL OR product_id = $3)
|
||||
AND status = 'pending'
|
||||
AND (expires_at IS NULL OR expires_at > NOW())
|
||||
ORDER BY created_at DESC
|
||||
LIMIT 1
|
||||
`, [userId, paymentType]);
|
||||
`, [userId, paymentType, productId || null]);
|
||||
return result.rows[0] || null;
|
||||
}
|
||||
|
||||
@@ -409,7 +486,10 @@ class GameModeManager {
|
||||
if (!packageInfo) return null;
|
||||
return {
|
||||
...packageInfo,
|
||||
price: typeof packageInfo.price === 'bigint' ? Number(packageInfo.price) : packageInfo.price
|
||||
price: typeof packageInfo.price === 'bigint' ? Number(packageInfo.price) : packageInfo.price,
|
||||
grants: ProductGrants.publicGrantSummary(ProductGrants.normalizeProductGrants(packageInfo, {
|
||||
credits: Number(packageInfo.credits || 0) + Number(packageInfo.bonus || 0)
|
||||
}))
|
||||
};
|
||||
}
|
||||
|
||||
@@ -425,6 +505,8 @@ class GameModeManager {
|
||||
expiresAt: row.expires_at,
|
||||
paymentType,
|
||||
description: row.description,
|
||||
productId: row.product_id || null,
|
||||
grants: row.product_grants || null,
|
||||
package: this._serializePackageInfo(packageInfo),
|
||||
reused: true
|
||||
};
|
||||
@@ -823,7 +905,7 @@ class GameModeManager {
|
||||
total_games_played = total_games_played + 1,
|
||||
updated_at = NOW()
|
||||
WHERE id = $2 AND credits >= $1
|
||||
RETURNING credits
|
||||
RETURNING credits, total_credits_purchased
|
||||
`, [creditsToSpend, user.id]);
|
||||
|
||||
if (updateRes.rows.length === 0) {
|
||||
@@ -831,6 +913,7 @@ class GameModeManager {
|
||||
}
|
||||
|
||||
const remainingCredits = updateRes.rows[0].credits;
|
||||
const totalCreditsPurchased = updateRes.rows[0].total_credits_purchased || user.total_credits_purchased || 0;
|
||||
|
||||
await client.query(`
|
||||
UPDATE games SET game_mode = 'PAID_CREDITS', payout_address = $2,
|
||||
@@ -844,7 +927,7 @@ class GameModeManager {
|
||||
VALUES ($1, $2, 'game_entry', $3, 'spend')
|
||||
`, [user.id, -creditsToSpend, remainingCredits]);
|
||||
|
||||
return { remainingCredits };
|
||||
return { remainingCredits, totalCreditsPurchased };
|
||||
});
|
||||
|
||||
if (result.insufficient) {
|
||||
@@ -861,6 +944,7 @@ class GameModeManager {
|
||||
return {
|
||||
success: true,
|
||||
creditsRemaining: result.remainingCredits,
|
||||
totalCreditsPurchased: result.totalCreditsPurchased,
|
||||
creditsSpent: creditsToSpend,
|
||||
effectiveMode: 'PAID_CREDITS'
|
||||
};
|
||||
@@ -915,11 +999,14 @@ class GameModeManager {
|
||||
let amount;
|
||||
let description;
|
||||
let packageInfo = null;
|
||||
let productId = null;
|
||||
let productGrants = ProductGrants.normalizeProductGrants({}, { credits: 0 });
|
||||
|
||||
switch (paymentType) {
|
||||
case 'single_game': {
|
||||
amount = this.singleGamePrice;
|
||||
description = `${this.gameName} single game entry (${this.currencyLabel})`;
|
||||
productId = 'single_game';
|
||||
break;
|
||||
}
|
||||
case 'credits_package': {
|
||||
@@ -939,12 +1026,31 @@ class GameModeManager {
|
||||
const packagePrice = selectedPackage?.price ?? this.creditsPackagePrice;
|
||||
amount = typeof packagePrice === 'bigint' ? Number(packagePrice) : Number(packagePrice);
|
||||
packageInfo = selectedPackage;
|
||||
productId = selectedPackage?.id || 'credits_package';
|
||||
const creditCount = selectedPackage?.credits ?? 10;
|
||||
const bonusCredits = selectedPackage?.bonus ?? 0;
|
||||
productGrants = ProductGrants.normalizeProductGrants(selectedPackage, {
|
||||
credits: Number(creditCount) + Number(bonusCredits || 0)
|
||||
});
|
||||
const bonusText = bonusCredits > 0 ? ` (+${bonusCredits} bonus)` : '';
|
||||
description = `${this.gameName} ${creditCount}${bonusText} credits package (${this.currencyLabel})`;
|
||||
break;
|
||||
}
|
||||
case 'cosmetic_pack': {
|
||||
const product = this.getCosmeticProduct(options.productId || options.packageId);
|
||||
if (!product) {
|
||||
throw new ValidationError('Unknown cosmetic product requested', {
|
||||
safeMessage: 'Unsupported product requested.'
|
||||
});
|
||||
}
|
||||
const price = product.price ?? 0;
|
||||
amount = typeof price === 'bigint' ? Number(price) : Number(price);
|
||||
packageInfo = product;
|
||||
productId = product.id;
|
||||
productGrants = ProductGrants.normalizeProductGrants(product, { credits: 0 });
|
||||
description = `${this.gameName} ${product.label || product.id} (${this.currencyLabel})`;
|
||||
break;
|
||||
}
|
||||
default:
|
||||
throw new ValidationError(`Invalid payment type requested: ${paymentType}`, {
|
||||
safeMessage: 'Unsupported payment type requested.'
|
||||
@@ -952,7 +1058,7 @@ class GameModeManager {
|
||||
}
|
||||
|
||||
if (reuseExisting) {
|
||||
const existingRow = await this._findReusablePayment(user.id, paymentType);
|
||||
const existingRow = await this._findReusablePayment(user.id, paymentType, productId);
|
||||
if (existingRow) {
|
||||
const existing = this._mapPaymentRowToRequest(existingRow, paymentType, packageInfo);
|
||||
if (existing && !existing.description) {
|
||||
@@ -983,10 +1089,21 @@ class GameModeManager {
|
||||
|
||||
// Store payment info in database (address_index enables monitoring restoration after restart)
|
||||
const insertResult = await this.db.query(`
|
||||
INSERT INTO payments (user_id, socket_id, subaddress, expected_amount, payment_type, status, description, created_at, expires_at, address_index)
|
||||
VALUES ($1, $2, $3, $4, $5, 'pending', $6, NOW(), $7, $8)
|
||||
INSERT INTO payments (user_id, socket_id, subaddress, expected_amount, payment_type, status, description, created_at, expires_at, address_index, product_id, product_grants)
|
||||
VALUES ($1, $2, $3, $4, $5, 'pending', $6, NOW(), $7, $8, $9, $10::jsonb)
|
||||
RETURNING id, expires_at
|
||||
`, [user.id, socketId, paymentResult.address, amount, paymentType, description, expiresAt, paymentResult.addressIndex ?? null]);
|
||||
`, [
|
||||
user.id,
|
||||
socketId,
|
||||
paymentResult.address,
|
||||
amount,
|
||||
paymentType,
|
||||
description,
|
||||
expiresAt,
|
||||
paymentResult.addressIndex ?? null,
|
||||
productId,
|
||||
JSON.stringify(ProductGrants.serializeProductGrants(productGrants))
|
||||
]);
|
||||
|
||||
const insertedRow = insertResult.rows[0];
|
||||
|
||||
@@ -999,6 +1116,8 @@ class GameModeManager {
|
||||
expiresAt: insertedRow?.expires_at || expiresAt,
|
||||
package: this._serializePackageInfo(packageInfo),
|
||||
paymentType,
|
||||
productId,
|
||||
grants: ProductGrants.publicGrantSummary(productGrants),
|
||||
description,
|
||||
reused: false,
|
||||
expiredAddresses
|
||||
@@ -1150,14 +1269,28 @@ class GameModeManager {
|
||||
const packages = this.configSnapshot?.modes?.credits?.packages || [];
|
||||
const creditPackages = packages.map(pkg => ({
|
||||
id: pkg.id,
|
||||
label: pkg.label || pkg.id,
|
||||
credits: pkg.credits,
|
||||
price: typeof pkg.price === 'bigint' ? Number(pkg.price) : pkg.price,
|
||||
bonus: pkg.bonus || 0,
|
||||
grants: ProductGrants.publicGrantSummary(ProductGrants.normalizeProductGrants(pkg, {
|
||||
credits: Number(pkg.credits || 0) + Number(pkg.bonus || 0)
|
||||
})),
|
||||
priceFormatted: this.formatAtomicHuman(
|
||||
typeof pkg.price === 'bigint' ? Number(pkg.price) : pkg.price,
|
||||
2
|
||||
)
|
||||
}));
|
||||
const cosmeticProducts = this.getCosmeticProducts().map(product => ({
|
||||
id: product.id,
|
||||
label: product.label || product.id,
|
||||
price: typeof product.price === 'bigint' ? Number(product.price) : product.price,
|
||||
grants: ProductGrants.publicGrantSummary(ProductGrants.normalizeProductGrants(product, { credits: 0 })),
|
||||
priceFormatted: this.formatAtomicHuman(
|
||||
typeof product.price === 'bigint' ? Number(product.price) : product.price,
|
||||
2
|
||||
)
|
||||
}));
|
||||
|
||||
return {
|
||||
mode: this.gameMode,
|
||||
@@ -1172,6 +1305,7 @@ class GameModeManager {
|
||||
creditsPackagePrice: this.creditsPackagePrice,
|
||||
creditsPerGame: this.creditsPerGameCost,
|
||||
creditPackages: creditPackages,
|
||||
cosmeticProducts: cosmeticProducts,
|
||||
creditsPayoutBaseValue: this.creditsPayoutBaseValue,
|
||||
paymentsEnabled: this.paymentsEnabled,
|
||||
freePlayEnabled: this.freePlayEnabled,
|
||||
@@ -1196,7 +1330,15 @@ class GameModeManager {
|
||||
// Smirk wallet integration. Smirk only works on mainnet, so it is forced off on
|
||||
// any test network (stagenet/testnet) regardless of SMIRK_ENABLED.
|
||||
smirkEnabled: process.env.SMIRK_ENABLED !== 'false' && !this.isTestNetwork,
|
||||
explorerTxUrl: process.env.EXPLORER_TX_URL || null
|
||||
explorerTxUrl: process.env.EXPLORER_TX_URL || null,
|
||||
// Which top-level modes this instance offers. Solo (the single-player dungeon) is
|
||||
// on unless explicitly disabled; Tavern and Multiplayer are opt-in. The client uses
|
||||
// this to show/hide entry points, so any single mode can run on its own.
|
||||
modes: {
|
||||
solo: process.env.SOLO_ENABLED !== 'false',
|
||||
tavern: process.env.TAVERN_ENABLED === 'true',
|
||||
multiplayer: process.env.MULTIPLAYER_ENABLED === 'true'
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
+6
-1
@@ -74,7 +74,7 @@ app.use((req, res, next) => {
|
||||
"style-src 'self' 'unsafe-inline'",
|
||||
"img-src 'self' data:",
|
||||
"font-src 'self'",
|
||||
"connect-src 'self' https://smirk.cash",
|
||||
"connect-src 'self' https://smirk.cash https://cdn.socket.io https://cdn.jsdelivr.net",
|
||||
"object-src 'none'",
|
||||
"base-uri 'self'",
|
||||
"frame-ancestors 'self'",
|
||||
@@ -104,6 +104,11 @@ app.get('/', function(req, res) {
|
||||
res.sendFile('index.html', { root: htmlPath });
|
||||
});
|
||||
|
||||
// Human-friendly tavern route. The static file remains /tavern.html for direct asset serving.
|
||||
app.get(['/tavern', '/tavern/'], function(req, res) {
|
||||
res.sendFile('tavern.html', { root: htmlPath });
|
||||
});
|
||||
|
||||
// Serve admin panel
|
||||
app.get('/admin', function(req, res) {
|
||||
res.sendFile('admin.html', { root: htmlPath });
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
-- Migration 020: Canonical cosmetic identity and pack entitlements.
|
||||
--
|
||||
-- `users.appearance` stores the normalized public cosmetic identity used by tavern,
|
||||
-- future PvP rooms, and eventually single-player rendering. `user_pack_entitlements`
|
||||
-- is the operator/admin override table for individual premium pack unlocks. The
|
||||
-- current default premium policy still comes from users.total_credits_purchased > 0.
|
||||
|
||||
ALTER TABLE users
|
||||
ADD COLUMN IF NOT EXISTS appearance JSONB NOT NULL DEFAULT
|
||||
'{"avatar":"default","tint":"none","equipment":{"body":"none","head":"none","shield":"none","weapon":"none"}}'::jsonb;
|
||||
|
||||
ALTER TABLE users
|
||||
ADD COLUMN IF NOT EXISTS premium_level VARCHAR(32) NOT NULL DEFAULT 'free';
|
||||
|
||||
CREATE TABLE IF NOT EXISTS user_pack_entitlements (
|
||||
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
pack_id VARCHAR(80) NOT NULL,
|
||||
source VARCHAR(40) NOT NULL DEFAULT 'operator',
|
||||
granted_at TIMESTAMP NOT NULL DEFAULT NOW(),
|
||||
expires_at TIMESTAMP NULL,
|
||||
metadata JSONB NOT NULL DEFAULT '{}'::jsonb,
|
||||
PRIMARY KEY (user_id, pack_id)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_user_pack_entitlements_user_id
|
||||
ON user_pack_entitlements(user_id);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_user_pack_entitlements_active
|
||||
ON user_pack_entitlements(user_id, pack_id)
|
||||
WHERE expires_at IS NULL;
|
||||
|
||||
COMMENT ON COLUMN users.appearance IS 'Normalized cosmetic identity: avatar, tint, equipment.';
|
||||
COMMENT ON COLUMN users.premium_level IS 'Operator-defined premium tier; free by default. Credit purchases also unlock preview premium packs.';
|
||||
COMMENT ON TABLE user_pack_entitlements IS 'Per-user premium cosmetic/render pack grants for future individual pack purchases or operator unlocks.';
|
||||
@@ -0,0 +1,23 @@
|
||||
-- Migration 021: Durable product grants on payments.
|
||||
--
|
||||
-- A payment product may grant credits, cosmetic/render packs, and/or a premium level.
|
||||
-- Persist the product id and normalized grants on the payment row so confirmation/recovery
|
||||
-- does not depend on in-memory socket state.
|
||||
|
||||
ALTER TABLE payments
|
||||
ADD COLUMN IF NOT EXISTS product_id VARCHAR(100);
|
||||
|
||||
ALTER TABLE payments
|
||||
ADD COLUMN IF NOT EXISTS product_grants JSONB NOT NULL DEFAULT '{}'::jsonb;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_payments_product_id
|
||||
ON payments(product_id);
|
||||
|
||||
-- Allow standalone cosmetic purchases without granting a game entry or credits.
|
||||
ALTER TABLE payments DROP CONSTRAINT IF EXISTS payments_payment_type_check;
|
||||
ALTER TABLE payments
|
||||
ADD CONSTRAINT payments_payment_type_check
|
||||
CHECK (payment_type IN ('single_game', 'credits_package', 'cosmetic_pack')) NOT VALID;
|
||||
|
||||
COMMENT ON COLUMN payments.product_id IS 'Operator product id used to create this payment request.';
|
||||
COMMENT ON COLUMN payments.product_grants IS 'Normalized grant payload applied when this payment confirms.';
|
||||
@@ -0,0 +1,52 @@
|
||||
/**
|
||||
* Occupant — a player's avatar inside a real-time Room (Tavern or Multiplayer match).
|
||||
*
|
||||
* The multiplayer analogue of game/player.js, but for a shared world: many Occupants
|
||||
* live in one Room and everyone sees everyone move. Kept small and dependency-free so the
|
||||
* engine can be unit-tested in isolation and reused independently.
|
||||
*/
|
||||
class Occupant {
|
||||
/**
|
||||
* @param {string} id Stable identity (socket id today; Smirk/wallet key later).
|
||||
* @param {object} opts
|
||||
* @param {number} [opts.x]
|
||||
* @param {number} [opts.y]
|
||||
* @param {string} [opts.name] Display name (null = anonymous).
|
||||
* @param {string} [opts.avatar] Avatar id (cosmetic; unlock-gated by Operator Policy).
|
||||
* @param {object} [opts.appearance] Structured cosmetic appearance (base + tint/equipment).
|
||||
* @param {string} [opts.facing] 'up' | 'down' | 'left' | 'right'
|
||||
*/
|
||||
constructor(id, { x = 0, y = 0, name = null, avatar = 'default', appearance = null, facing = 'down' } = {}) {
|
||||
this.id = id;
|
||||
this.x = x;
|
||||
this.y = y;
|
||||
this.name = name;
|
||||
this.avatar = avatar;
|
||||
this.appearance = appearance;
|
||||
this.facing = facing;
|
||||
this.joinedAt = Date.now();
|
||||
this.lastMoveAt = 0;
|
||||
}
|
||||
|
||||
moveTo(x, y, facing = null) {
|
||||
this.x = x;
|
||||
this.y = y;
|
||||
if (facing) this.facing = facing;
|
||||
this.lastMoveAt = Date.now();
|
||||
}
|
||||
|
||||
/** Broadcast-safe state (everything here is public to the whole room). */
|
||||
getState() {
|
||||
return {
|
||||
id: this.id,
|
||||
x: this.x,
|
||||
y: this.y,
|
||||
name: this.name,
|
||||
avatar: this.avatar,
|
||||
appearance: this.appearance,
|
||||
facing: this.facing
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = Occupant;
|
||||
@@ -0,0 +1,214 @@
|
||||
const { v4: uuidv4 } = require('uuid');
|
||||
const Occupant = require('./Occupant');
|
||||
const { TAVERN_LAYOUT, FLOOR_CHARS } = require('./tavernMap');
|
||||
|
||||
const CONSOLE_LOGGING = process.env.NODE_ENV === 'debug' || process.env.NODE_ENV === 'development';
|
||||
|
||||
/**
|
||||
* Room — a shared, real-time, multi-occupant world. Shared engine for both new modes:
|
||||
*
|
||||
* • Tavern (type 'tavern'): a peaceful room — walk around, chat, spectate.
|
||||
* • Multiplayer (type 'match'): the same engine with a dungeon, monsters, hazards and
|
||||
* combat added (later milestones).
|
||||
*
|
||||
* Design invariants (kept transport-agnostic so the engine is testable and reusable):
|
||||
* • No Socket.IO / DB / Wownerogue coupling here — game-state logic only. A manager layer
|
||||
* owns transport (Socket.IO rooms, broadcasts) and the server-tick timer.
|
||||
* • Server-authoritative movement: the client requests a step; the Room decides.
|
||||
* • Serialisable: snapshot()/fullState() are broadcast-safe (no engine internals).
|
||||
*/
|
||||
class Room {
|
||||
/**
|
||||
* @param {object} opts
|
||||
* @param {string} [opts.id] Room id (defaults to a uuid).
|
||||
* @param {string} [opts.type] 'tavern' | 'match' (informational for now).
|
||||
* @param {string[]} [opts.layout] Map rows (defaults to the tavern).
|
||||
* @param {boolean} [opts.solidOccupants] If true, occupants block each other's tiles
|
||||
* (matches). Tavern leaves this false so players
|
||||
* can't grief by blocking doorways.
|
||||
* @param {number} [opts.maxOccupants]
|
||||
*/
|
||||
constructor({ id = null, type = 'tavern', layout = TAVERN_LAYOUT, solidOccupants = false, maxOccupants = 50, roomData = null, roomUrl = null } = {}) {
|
||||
this.id = id || uuidv4();
|
||||
this.type = type;
|
||||
this.solidOccupants = solidOccupants;
|
||||
this.maxOccupants = maxOccupants;
|
||||
this.createdAt = Date.now();
|
||||
this.tickCount = 0;
|
||||
this.roomUrl = roomUrl; // client-relative URL of the designed room (if any)
|
||||
|
||||
// A designed room (imported .tmx) supplies dims + a walkability grid; otherwise build
|
||||
// the walkable map from the ASCII layout.
|
||||
if (roomData) this._buildFromRoomData(roomData);
|
||||
else this._buildMap(layout);
|
||||
this.occupants = new Map(); // id -> Occupant
|
||||
}
|
||||
|
||||
_buildFromRoomData(rd) {
|
||||
this.roomData = rd;
|
||||
this.layout = null;
|
||||
this.rows = rd.rows;
|
||||
this.cols = rd.cols;
|
||||
this.walkable = rd.walkable;
|
||||
// Spawn on the walkable cells nearest the room centre, so players start together.
|
||||
const cx = this.cols / 2, cy = this.rows / 2, cells = [];
|
||||
for (let y = 0; y < this.rows; y++) {
|
||||
for (let x = 0; x < this.cols; x++) {
|
||||
if (this.walkable[y] && this.walkable[y][x] === true) {
|
||||
cells.push({ x, y, d: (x - cx) * (x - cx) + (y - cy) * (y - cy) });
|
||||
}
|
||||
}
|
||||
}
|
||||
cells.sort((a, b) => a.d - b.d);
|
||||
this.spawns = cells.slice(0, 24).map(c => ({ x: c.x, y: c.y }));
|
||||
if (this.spawns.length === 0) this.spawns = [{ x: 1, y: 1 }];
|
||||
}
|
||||
|
||||
_buildMap(layout) {
|
||||
this.layout = layout;
|
||||
this.rows = layout.length;
|
||||
this.cols = layout.reduce((m, r) => Math.max(m, r.length), 0);
|
||||
this.spawns = [];
|
||||
this.walkable = []; // walkable[y][x] === true means floor
|
||||
for (let y = 0; y < this.rows; y++) {
|
||||
const row = [];
|
||||
for (let x = 0; x < this.cols; x++) {
|
||||
const ch = layout[y][x] || '#'; // treat short rows as walled
|
||||
row.push(FLOOR_CHARS.has(ch));
|
||||
if (ch === '@') this.spawns.push({ x, y });
|
||||
}
|
||||
this.walkable.push(row);
|
||||
}
|
||||
if (this.spawns.length === 0) {
|
||||
// Fall back to the first walkable tile.
|
||||
for (let y = 0; y < this.rows && this.spawns.length === 0; y++) {
|
||||
for (let x = 0; x < this.cols; x++) {
|
||||
if (this.walkable[y][x]) { this.spawns.push({ x, y }); break; }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
isWalkable(x, y) {
|
||||
if (y < 0 || y >= this.rows || x < 0 || x >= this.cols) return false;
|
||||
return this.walkable[y][x] === true;
|
||||
}
|
||||
|
||||
isOccupied(x, y, exceptId = null) {
|
||||
for (const occ of this.occupants.values()) {
|
||||
if (occ.id !== exceptId && occ.x === x && occ.y === y) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
_pickSpawn() {
|
||||
// Prefer an unoccupied spawn tile so joiners don't stack; else any spawn.
|
||||
for (const s of this.spawns) {
|
||||
if (!this.isOccupied(s.x, s.y)) return s;
|
||||
}
|
||||
return this.spawns[0] || { x: 0, y: 0 };
|
||||
}
|
||||
|
||||
/**
|
||||
* @returns {Occupant|null} the occupant, or null if the room is full.
|
||||
*/
|
||||
addOccupant(id, { name = null, avatar = 'default', appearance = null } = {}) {
|
||||
if (this.occupants.has(id)) return this.occupants.get(id);
|
||||
if (this.occupants.size >= this.maxOccupants) return null;
|
||||
const spawn = this._pickSpawn();
|
||||
const occ = new Occupant(id, { x: spawn.x, y: spawn.y, name, avatar, appearance });
|
||||
this.occupants.set(id, occ);
|
||||
if (CONSOLE_LOGGING) {
|
||||
console.log(`[Room ${String(this.id).slice(0, 8)}] +occupant ${String(id).slice(0, 6)} at (${spawn.x},${spawn.y})`);
|
||||
}
|
||||
return occ;
|
||||
}
|
||||
|
||||
removeOccupant(id) {
|
||||
return this.occupants.delete(id);
|
||||
}
|
||||
|
||||
getOccupant(id) {
|
||||
return this.occupants.get(id) || null;
|
||||
}
|
||||
|
||||
static facingFor(dx, dy) {
|
||||
if (dx === -1) return 'left';
|
||||
if (dx === 1) return 'right';
|
||||
if (dy === -1) return 'up';
|
||||
if (dy === 1) return 'down';
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Attempt a one-tile cardinal move for an occupant. Server-authoritative: the client
|
||||
* only requests a direction; here we validate bounds, walls and (optionally) other
|
||||
* occupants, and mutate state only if the step is legal.
|
||||
* @returns {{moved:boolean, reason?:string, occupant?:object}}
|
||||
*/
|
||||
moveOccupant(id, dx, dy) {
|
||||
const occ = this.occupants.get(id);
|
||||
if (!occ) return { moved: false, reason: 'not_in_room' };
|
||||
|
||||
dx = Math.sign(dx || 0);
|
||||
dy = Math.sign(dy || 0);
|
||||
if (Math.abs(dx) + Math.abs(dy) !== 1) return { moved: false, reason: 'invalid_step' };
|
||||
|
||||
const nx = occ.x + dx;
|
||||
const ny = occ.y + dy;
|
||||
const facing = Room.facingFor(dx, dy);
|
||||
|
||||
// Turn to face the attempted direction even when blocked (feels responsive).
|
||||
if (!this.isWalkable(nx, ny)) {
|
||||
if (facing) occ.facing = facing;
|
||||
return { moved: false, reason: 'blocked', occupant: occ.getState() };
|
||||
}
|
||||
if (this.solidOccupants && this.isOccupied(nx, ny, id)) {
|
||||
if (facing) occ.facing = facing;
|
||||
return { moved: false, reason: 'occupied', occupant: occ.getState() };
|
||||
}
|
||||
|
||||
occ.moveTo(nx, ny, facing);
|
||||
return { moved: true, occupant: occ.getState() };
|
||||
}
|
||||
|
||||
/**
|
||||
* Advance the world one server tick. For a Tavern this is currently a heartbeat
|
||||
* (no autonomous entities yet). Multiplayer match rooms will drive monster movement,
|
||||
* environmental hazards and combat resolution here. Returns events for the manager
|
||||
* to broadcast. The hook is included from the start so those systems have a home.
|
||||
* @returns {{tick:number, events:Array}}
|
||||
*/
|
||||
tick() {
|
||||
this.tickCount++;
|
||||
return { tick: this.tickCount, events: [] };
|
||||
}
|
||||
|
||||
/** Occupants-only snapshot — broadcast every tick/update. */
|
||||
snapshot() {
|
||||
return {
|
||||
roomId: this.id,
|
||||
type: this.type,
|
||||
tick: this.tickCount,
|
||||
occupants: Array.from(this.occupants.values()).map(o => o.getState())
|
||||
};
|
||||
}
|
||||
|
||||
/** Full state including the static map — sent once when an occupant joins. */
|
||||
fullState() {
|
||||
return {
|
||||
...this.snapshot(),
|
||||
cols: this.cols,
|
||||
rows: this.rows,
|
||||
layout: this.layout,
|
||||
solidOccupants: this.solidOccupants,
|
||||
roomUrl: this.roomUrl || null
|
||||
};
|
||||
}
|
||||
|
||||
get size() {
|
||||
return this.occupants.size;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = Room;
|
||||
@@ -0,0 +1,100 @@
|
||||
const COLOR_AVATARS = ['default', 'green', 'amber', 'red'];
|
||||
const PREMIUM_SKINS = ['monero-knight', 'wownero-rogue', 'cypher-operative'];
|
||||
const MODEL3D_AVATARS = ['kenney-survivor-male', 'kenney-survivor-female'];
|
||||
const CHAR_AVATARS = [
|
||||
'char-villager', 'char-elder', 'char-barbarian', 'char-monk', 'char-ranger',
|
||||
'char-bard', 'char-rogue', 'char-merchant', 'char-wizard', 'char-goblin'
|
||||
];
|
||||
|
||||
const CHAR_TINTS = ['none', 'rose', 'teal', 'moss', 'gold', 'violet', 'ash'];
|
||||
const CHAR_EQUIPMENT_SLOTS = ['body', 'head', 'shield', 'weapon'];
|
||||
const CHAR_EQUIPMENT = {
|
||||
body: ['none', 'robe', 'jerkin', 'mail', 'sash'],
|
||||
head: ['none', 'hood', 'helm', 'horns', 'cap'],
|
||||
shield: ['none', 'round', 'kite', 'tower', 'buckler'],
|
||||
weapon: ['none', 'staff', 'sword', 'axe', 'bow']
|
||||
};
|
||||
|
||||
const ALL_AVATARS = [...COLOR_AVATARS, ...PREMIUM_SKINS, ...CHAR_AVATARS, ...MODEL3D_AVATARS];
|
||||
const AVATAR_PACKS = Object.freeze({
|
||||
...PREMIUM_SKINS.reduce((out, id) => {
|
||||
out[id] = 'generated-skins';
|
||||
return out;
|
||||
}, {}),
|
||||
...MODEL3D_AVATARS.reduce((out, id) => {
|
||||
out[id] = 'kenney-3d-characters';
|
||||
return out;
|
||||
}, {})
|
||||
});
|
||||
const DEFAULT_EQUIPMENT = CHAR_EQUIPMENT_SLOTS.reduce((out, slot) => {
|
||||
out[slot] = 'none';
|
||||
return out;
|
||||
}, {});
|
||||
|
||||
function includes(list, id) {
|
||||
return list.indexOf(id) !== -1;
|
||||
}
|
||||
|
||||
function isValidAvatar(id) {
|
||||
return includes(ALL_AVATARS, id);
|
||||
}
|
||||
|
||||
function isCharAvatar(id) {
|
||||
return includes(CHAR_AVATARS, id);
|
||||
}
|
||||
|
||||
function isPremiumAvatar(id) {
|
||||
return !!AVATAR_PACKS[id];
|
||||
}
|
||||
|
||||
function avatarPack(id) {
|
||||
return AVATAR_PACKS[id] || null;
|
||||
}
|
||||
|
||||
function normalizeEquipment(input = {}) {
|
||||
const out = {};
|
||||
for (const slot of CHAR_EQUIPMENT_SLOTS) {
|
||||
const id = input && typeof input[slot] === 'string' ? input[slot] : 'none';
|
||||
out[slot] = includes(CHAR_EQUIPMENT[slot], id) ? id : 'none';
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function normalizeAppearance(input = {}) {
|
||||
if (input && input.appearance && !input.avatar) input = input.appearance;
|
||||
if (typeof input === 'string') input = { avatar: input };
|
||||
if (!input || typeof input !== 'object') input = {};
|
||||
|
||||
let avatar = input.avatar || input.id || 'default';
|
||||
if (!isValidAvatar(avatar)) avatar = 'default';
|
||||
|
||||
if (!isCharAvatar(avatar)) {
|
||||
return { avatar, tint: 'none', equipment: { ...DEFAULT_EQUIPMENT } };
|
||||
}
|
||||
|
||||
const tint = includes(CHAR_TINTS, input.tint) ? input.tint : 'none';
|
||||
return {
|
||||
avatar,
|
||||
tint,
|
||||
equipment: normalizeEquipment(input.equipment)
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
COLOR_AVATARS,
|
||||
PREMIUM_SKINS,
|
||||
MODEL3D_AVATARS,
|
||||
CHAR_AVATARS,
|
||||
CHAR_TINTS,
|
||||
CHAR_EQUIPMENT,
|
||||
CHAR_EQUIPMENT_SLOTS,
|
||||
DEFAULT_EQUIPMENT,
|
||||
avatarIds: () => ALL_AVATARS.slice(),
|
||||
premiumAvatarIds: () => Object.keys(AVATAR_PACKS),
|
||||
avatarPack,
|
||||
isValidAvatar,
|
||||
isCharAvatar,
|
||||
isPremiumAvatar,
|
||||
normalizeEquipment,
|
||||
normalizeAppearance
|
||||
};
|
||||
@@ -0,0 +1,127 @@
|
||||
const Appearance = require('./appearance');
|
||||
|
||||
const PACKS = Object.freeze({
|
||||
'roguelike-interior': Object.freeze({
|
||||
id: 'roguelike-interior',
|
||||
label: 'Kenney Roguelike Interior',
|
||||
premium: false,
|
||||
projection: 'topdown'
|
||||
}),
|
||||
'generated-skins': Object.freeze({
|
||||
id: 'generated-skins',
|
||||
label: 'Premium Generated Skins',
|
||||
premium: true,
|
||||
projection: 'topdown',
|
||||
unlock: { kind: 'credits_purchase', minTotalCreditsPurchased: 1 }
|
||||
}),
|
||||
'iso-dungeon': Object.freeze({
|
||||
id: 'iso-dungeon',
|
||||
label: 'Kenney Isometric Dungeon',
|
||||
premium: true,
|
||||
projection: 'iso',
|
||||
unlock: { kind: 'credits_purchase', minTotalCreditsPurchased: 1 }
|
||||
}),
|
||||
'kenney-3d-characters': Object.freeze({
|
||||
id: 'kenney-3d-characters',
|
||||
label: 'Kenney Animated 3D Characters',
|
||||
premium: true,
|
||||
projection: '3d',
|
||||
unlock: { kind: 'credits_purchase', minTotalCreditsPurchased: 1 }
|
||||
})
|
||||
});
|
||||
|
||||
const PREMIUM_LEVELS = new Set(['credits', 'supporter', 'premium', 'operator']);
|
||||
|
||||
function asNumber(v) {
|
||||
const n = Number(v || 0);
|
||||
return Number.isFinite(n) ? n : 0;
|
||||
}
|
||||
|
||||
function normalizePackGrants(grants = []) {
|
||||
const out = {};
|
||||
if (Array.isArray(grants)) {
|
||||
for (const g of grants) {
|
||||
const id = g && (g.pack_id || g.packId || g.id);
|
||||
if (id && PACKS[id]) out[id] = true;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
if (grants && typeof grants === 'object') {
|
||||
for (const id of Object.keys(grants)) {
|
||||
if (PACKS[id] && grants[id]) out[id] = true;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function levelForUser(user = {}) {
|
||||
const raw = String(user.premium_level || user.premiumLevel || '').trim().toLowerCase();
|
||||
if (raw) return raw;
|
||||
return asNumber(user.total_credits_purchased || user.totalCreditsPurchased) > 0 ? 'credits' : 'free';
|
||||
}
|
||||
|
||||
function snapshotForUser(user = {}, packGrants = []) {
|
||||
const totalCreditsPurchased = asNumber(user.total_credits_purchased || user.totalCreditsPurchased);
|
||||
const credits = asNumber(user.credits);
|
||||
const level = levelForUser(user);
|
||||
const explicit = normalizePackGrants(packGrants);
|
||||
const hasCreditUnlock = totalCreditsPurchased > 0;
|
||||
const hasPremiumLevel = PREMIUM_LEVELS.has(level);
|
||||
const packs = {};
|
||||
|
||||
for (const id of Object.keys(PACKS)) {
|
||||
const pack = PACKS[id];
|
||||
if (!pack.premium) {
|
||||
packs[id] = true;
|
||||
continue;
|
||||
}
|
||||
const unlock = pack.unlock || {};
|
||||
const unlockedByCredits = unlock.kind === 'credits_purchase'
|
||||
&& hasCreditUnlock
|
||||
&& totalCreditsPurchased >= (unlock.minTotalCreditsPurchased || 1);
|
||||
packs[id] = !!explicit[id] || unlockedByCredits || hasPremiumLevel;
|
||||
}
|
||||
|
||||
const premiumPackUnlocked = Object.keys(packs).some(id => PACKS[id].premium && packs[id]);
|
||||
return {
|
||||
premium: hasCreditUnlock || hasPremiumLevel || premiumPackUnlocked,
|
||||
level: level === 'free' && hasCreditUnlock ? 'credits' : level,
|
||||
credits,
|
||||
totalCreditsPurchased,
|
||||
packs
|
||||
};
|
||||
}
|
||||
|
||||
function canUsePack(entitlements = {}, packId) {
|
||||
const pack = PACKS[packId];
|
||||
if (!pack) return false;
|
||||
if (!pack.premium) return true;
|
||||
if (entitlements.packs && Object.prototype.hasOwnProperty.call(entitlements.packs, packId)) {
|
||||
return !!entitlements.packs[packId];
|
||||
}
|
||||
return !!entitlements.premium;
|
||||
}
|
||||
|
||||
function canUseAppearance(entitlements = {}, appearanceOrAvatar = {}) {
|
||||
const appearance = Appearance.normalizeAppearance(appearanceOrAvatar);
|
||||
const packId = Appearance.avatarPack(appearance.avatar);
|
||||
return !packId || canUsePack(entitlements, packId);
|
||||
}
|
||||
|
||||
function normalizeAppearance(input = {}, entitlements = {}) {
|
||||
const appearance = Appearance.normalizeAppearance(input);
|
||||
if (!canUseAppearance(entitlements, appearance)) {
|
||||
return Appearance.normalizeAppearance('default');
|
||||
}
|
||||
return appearance;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
PACKS,
|
||||
PREMIUM_LEVELS,
|
||||
snapshotForUser,
|
||||
canUsePack,
|
||||
canUseAppearance,
|
||||
normalizeAppearance,
|
||||
normalizePackGrants
|
||||
};
|
||||
@@ -0,0 +1,58 @@
|
||||
/**
|
||||
* Default Tavern layout — a small room with hand-placed props (bar, tables), generated
|
||||
* procedurally so every row is guaranteed the same width.
|
||||
*
|
||||
* Legend:
|
||||
* '#' wall '=' bar counter 'o' table / stool (all solid)
|
||||
* '.' floor '@' spawn point (walkable)
|
||||
*
|
||||
* Anything NOT in FLOOR_CHARS is treated as solid by the Room engine. The layout is
|
||||
* generated procedurally so every row is guaranteed the same width (ragged ASCII maps
|
||||
* are a classic source of off-by-one collision bugs).
|
||||
*/
|
||||
|
||||
// Characters an Occupant may stand on.
|
||||
const FLOOR_CHARS = new Set(['.', '@']);
|
||||
|
||||
/**
|
||||
* Build the default tavern as an array of equal-length strings.
|
||||
* @param {number} cols
|
||||
* @param {number} rows
|
||||
* @returns {string[]}
|
||||
*/
|
||||
function buildDefaultTavern(cols = 26, rows = 13) {
|
||||
const grid = [];
|
||||
for (let y = 0; y < rows; y++) {
|
||||
const row = new Array(cols);
|
||||
for (let x = 0; x < cols; x++) {
|
||||
const border = x === 0 || y === 0 || x === cols - 1 || y === rows - 1;
|
||||
row[x] = border ? '#' : '.';
|
||||
}
|
||||
grid.push(row);
|
||||
}
|
||||
|
||||
const put = (x, y, ch) => {
|
||||
if (grid[y] && grid[y][x] !== undefined && grid[y][x] !== '#') grid[y][x] = ch;
|
||||
};
|
||||
|
||||
// Bar counter along the top interior wall.
|
||||
for (let x = 3; x <= 16; x++) put(x, 2, '=');
|
||||
|
||||
// Table + stool clusters (2x2 blocks of 'o').
|
||||
const tables = [[5, 5], [12, 5], [18, 5], [5, 9], [12, 9], [18, 9]];
|
||||
for (const [tx, ty] of tables) {
|
||||
put(tx, ty, 'o'); put(tx + 1, ty, 'o');
|
||||
put(tx, ty + 1, 'o'); put(tx + 1, ty + 1, 'o');
|
||||
}
|
||||
|
||||
// Spawn pad near the entrance (bottom-center). Two tiles so early tests have a
|
||||
// deterministic adjacent pair to exercise occupant-collision rules.
|
||||
put(12, 11, '@');
|
||||
put(13, 11, '@');
|
||||
|
||||
return grid.map(r => r.join(''));
|
||||
}
|
||||
|
||||
const TAVERN_LAYOUT = buildDefaultTavern();
|
||||
|
||||
module.exports = { TAVERN_LAYOUT, FLOOR_CHARS, buildDefaultTavern };
|
||||
@@ -0,0 +1,45 @@
|
||||
/**
|
||||
* ChatProvider — abstraction over chat message delivery and history.
|
||||
*
|
||||
* The seam that lets the chat backend be swapped (e.g. for a Nostr channel) without changing
|
||||
* callers. Application concerns — commands, moderation, rate limiting, XSS escaping — stay in
|
||||
* the caller (ChatHandler / TavernManager); a provider only delivers and (optionally) stores.
|
||||
*
|
||||
* Scopes:
|
||||
* 'global' → the whole server (the main lobby chat).
|
||||
* 'tavern:<id>' → a single Socket.IO room (tavern chat), ephemeral by default.
|
||||
*/
|
||||
class ChatProvider {
|
||||
// eslint-disable-next-line no-empty-function
|
||||
async initialize() {}
|
||||
|
||||
/**
|
||||
* Deliver (and optionally persist) a chat message.
|
||||
* @param {object} msg
|
||||
* @param {string} msg.scope 'global' or a room channel.
|
||||
* @param {string} msg.username Display name / short id.
|
||||
* @param {string} msg.text Message text (caller has already sanitized/escaped it).
|
||||
* @param {number} [msg.ts] Timestamp (ms).
|
||||
* @param {string} [msg.socketId]
|
||||
* @param {number|null} [msg.userId]
|
||||
*/
|
||||
async publish(msg) { // eslint-disable-line no-unused-vars
|
||||
throw new Error('ChatProvider.publish not implemented');
|
||||
}
|
||||
|
||||
/**
|
||||
* Recent messages for a scope, oldest → newest.
|
||||
* @param {object} opts
|
||||
* @param {string} [opts.scope]
|
||||
* @param {number} [opts.limit]
|
||||
* @returns {Promise<Array>}
|
||||
*/
|
||||
async getHistory({ scope = 'global', limit = 50 } = {}) { // eslint-disable-line no-unused-vars
|
||||
return [];
|
||||
}
|
||||
|
||||
// eslint-disable-next-line no-empty-function
|
||||
async shutdown() {}
|
||||
}
|
||||
|
||||
module.exports = ChatProvider;
|
||||
@@ -0,0 +1,61 @@
|
||||
const ChatProvider = require('./ChatProvider');
|
||||
|
||||
/**
|
||||
* SocketChatProvider — the default ChatProvider, backed by Socket.IO for delivery and (for
|
||||
* global chat) the Postgres-backed ChatHistoryManager for persistence.
|
||||
*
|
||||
* Behaviour matches the pre-seam chat exactly:
|
||||
* • global scope → persist via the history manager + broadcast to everyone
|
||||
* (broadcastManager.broadcastChatMessage, i.e. io.emit 'chat_broadcast').
|
||||
* • room scope → deliver only to that Socket.IO room, ephemeral (no history).
|
||||
*
|
||||
* A history manager may be injected (so ChatHandler shares its existing instance) or omitted
|
||||
* (tavern chat, which is ephemeral). When omitted, this provider persists nothing.
|
||||
*/
|
||||
class SocketChatProvider extends ChatProvider {
|
||||
constructor({ io, broadcastManager = null, debugManager = null, historyManager = null } = {}) {
|
||||
super();
|
||||
this.io = io;
|
||||
this.broadcastManager = broadcastManager;
|
||||
this.debugManager = debugManager;
|
||||
this.history = historyManager; // null → ephemeral (no persistence)
|
||||
this._ownsHistory = false; // true only if this provider created the manager
|
||||
}
|
||||
|
||||
async initialize() {
|
||||
if (this._ownsHistory && this.history) await this.history.initialize();
|
||||
}
|
||||
|
||||
async publish(msg = {}) {
|
||||
const { scope = 'global', username, text, ts = Date.now(), socketId = null, userId = null } = msg;
|
||||
|
||||
if (scope === 'global') {
|
||||
if (this.history) {
|
||||
// Fire-and-forget persistence, exactly as before (must not block delivery).
|
||||
this.history.saveMessage({ socketId, username, message: text, type: 'chat', userId })
|
||||
.catch(err => console.error('Failed to save chat message:', err.message));
|
||||
}
|
||||
if (this.broadcastManager) {
|
||||
this.broadcastManager.broadcastChatMessage(username, text, ts, socketId);
|
||||
} else {
|
||||
this.io.emit('chat_broadcast', { username, message: text, timestamp: ts, socketId });
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Room-scoped (e.g. tavern): delivered only to occupants of that room. The `scope`
|
||||
// field lets a room client filter these from any global broadcasts it also receives.
|
||||
this.io.to(scope).emit('chat_broadcast', { username, message: text, timestamp: ts, socketId, scope });
|
||||
}
|
||||
|
||||
async getHistory({ scope = 'global', limit = 50 } = {}) {
|
||||
if (scope === 'global' && this.history) return this.history.getRecentMessages(limit);
|
||||
return [];
|
||||
}
|
||||
|
||||
async shutdown() {
|
||||
if (this._ownsHistory && this.history) this.history.shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = SocketChatProvider;
|
||||
+21
-11
@@ -4,6 +4,7 @@
|
||||
*/
|
||||
|
||||
const ChatHistoryManager = require('./chatHistoryManager');
|
||||
const SocketChatProvider = require('./chat/SocketChatProvider');
|
||||
const { clientIp, stableId } = require('./rateLimitContext');
|
||||
|
||||
class ChatHandler {
|
||||
@@ -23,7 +24,18 @@ class ChatHandler {
|
||||
debugManager: debugManager,
|
||||
maxHistoryMessages: 50
|
||||
});
|
||||
|
||||
|
||||
// Chat delivery + history go through a ChatProvider seam so the backend is swappable
|
||||
// (e.g. a Nostr channel later). The default provider shares the ChatHistoryManager
|
||||
// instance above, so ban checks / stats that read this.chatHistory keep working and
|
||||
// lifecycle (initialize/shutdown) stays owned here.
|
||||
this.chatProvider = new SocketChatProvider({
|
||||
io: this.io,
|
||||
broadcastManager: this.broadcastManager,
|
||||
debugManager: this.debugManager,
|
||||
historyManager: this.chatHistory
|
||||
});
|
||||
|
||||
// Memory leak prevention - cleanup old timestamps
|
||||
this._chatLastSent = new Map();
|
||||
this.chatCleanupInterval = setInterval(() => this.cleanupChatTimestamps(), 300000); // 5 minutes
|
||||
@@ -45,7 +57,7 @@ class ChatHandler {
|
||||
*/
|
||||
async sendChatHistoryToUser(socketId, messageCount = 50) {
|
||||
try {
|
||||
const messages = await this.chatHistory.getRecentMessages(messageCount);
|
||||
const messages = await this.chatProvider.getHistory({ scope: 'global', limit: messageCount });
|
||||
if (messages.length > 0) {
|
||||
this.io.to(socketId).emit('chat_history', { messages });
|
||||
if (this.debugManager?.CONSOLE_LOGGING) {
|
||||
@@ -319,18 +331,16 @@ class ChatHandler {
|
||||
.slice(0, MAX_MESSAGE_LENGTH);
|
||||
const username = socket.id.substring(0, 6);
|
||||
|
||||
// Save message to history with user_id (async, don't block broadcast)
|
||||
this.chatHistory.saveMessage({
|
||||
socketId: socket.id,
|
||||
// Deliver + persist through the chat provider (global scope). The provider saves to
|
||||
// history (fire-and-forget) and broadcasts, matching the previous inline behaviour.
|
||||
await this.chatProvider.publish({
|
||||
scope: 'global',
|
||||
username: username,
|
||||
message: safe,
|
||||
type: 'chat',
|
||||
text: safe,
|
||||
ts: now,
|
||||
socketId: socket.id,
|
||||
userId: userId
|
||||
}).catch(err => {
|
||||
console.error('Failed to save chat message:', err.message);
|
||||
});
|
||||
|
||||
this.broadcastManager.broadcastChatMessage(username, safe, now, socket.id);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -280,7 +280,8 @@ class ConnectionHandler {
|
||||
this.io.to(socket.id).emit('session_resumed', {
|
||||
token: sessionInfo.token,
|
||||
payoutAddress: sessionInfo.user.payout_address || null,
|
||||
credits: sessionInfo.user.credits || 0
|
||||
credits: sessionInfo.user.credits || 0,
|
||||
totalCreditsPurchased: sessionInfo.user.total_credits_purchased || 0
|
||||
});
|
||||
} else {
|
||||
this.io.to(socket.id).emit('session_token', { token: sessionInfo.token });
|
||||
@@ -298,6 +299,7 @@ class ConnectionHandler {
|
||||
// Credits convenience push (include creditsPerGame for games remaining calculation)
|
||||
this.io.to(socket.id).emit('credits_update', {
|
||||
balance: sessionInfo.user.credits || 0,
|
||||
totalCreditsPurchased: sessionInfo.user.total_credits_purchased || 0,
|
||||
creditsPerGame: this.gameModeManager?.creditsPerGameCost || 1
|
||||
});
|
||||
|
||||
@@ -391,4 +393,4 @@ class ConnectionHandler {
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = ConnectionHandler;
|
||||
module.exports = ConnectionHandler;
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
const Appearance = require('../multiplayer/appearance');
|
||||
const Entitlements = require('../multiplayer/entitlements');
|
||||
|
||||
function parseAppearance(value) {
|
||||
if (!value) return Appearance.normalizeAppearance('default');
|
||||
if (typeof value === 'string') {
|
||||
try {
|
||||
return Appearance.normalizeAppearance(JSON.parse(value));
|
||||
} catch (_) {
|
||||
return Appearance.normalizeAppearance('default');
|
||||
}
|
||||
}
|
||||
return Appearance.normalizeAppearance(value);
|
||||
}
|
||||
|
||||
class IdentityService {
|
||||
constructor({ db = null, gameModeManager = null, sessionManager = null, debugManager = null } = {}) {
|
||||
this.db = db || gameModeManager?.db || null;
|
||||
this.gameModeManager = gameModeManager;
|
||||
this.sessionManager = sessionManager;
|
||||
this.debugManager = debugManager;
|
||||
}
|
||||
|
||||
async userForSocket(socket) {
|
||||
if (!socket) return null;
|
||||
if (this.gameModeManager && typeof this.gameModeManager.getOrCreateUser === 'function') {
|
||||
return this.gameModeManager.getOrCreateUser(socket.id);
|
||||
}
|
||||
if (this.sessionManager && typeof this.sessionManager.getBySocket === 'function') {
|
||||
return this.sessionManager.getBySocket(socket.id);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
async packGrantsForUser(userId) {
|
||||
if (!this.db || userId == null) return [];
|
||||
try {
|
||||
const result = await this.db.query(`
|
||||
SELECT pack_id, source, granted_at, expires_at
|
||||
FROM user_pack_entitlements
|
||||
WHERE user_id = $1
|
||||
AND (expires_at IS NULL OR expires_at > NOW())
|
||||
`, [userId]);
|
||||
return result.rows || [];
|
||||
} catch (err) {
|
||||
// Fresh deployments run migrations before sockets are accepted. This fallback keeps
|
||||
// tests and partially-migrated dev DBs from losing the whole connection path.
|
||||
if (err && (err.code === '42P01' || /user_pack_entitlements/i.test(err.message || ''))) {
|
||||
if (this.debugManager?.CONSOLE_LOGGING) {
|
||||
console.warn('[IdentityService] user_pack_entitlements unavailable; using credit policy only.');
|
||||
}
|
||||
return [];
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
async entitlementsForUser(user) {
|
||||
if (!user) return Entitlements.snapshotForUser({});
|
||||
const grants = await this.packGrantsForUser(user.id);
|
||||
return Entitlements.snapshotForUser(user, grants);
|
||||
}
|
||||
|
||||
async entitlementsForSocket(socket) {
|
||||
const user = await this.userForSocket(socket);
|
||||
return this.entitlementsForUser(user);
|
||||
}
|
||||
|
||||
async identityForSocket(socket) {
|
||||
const user = await this.userForSocket(socket);
|
||||
const entitlements = await this.entitlementsForUser(user);
|
||||
const appearance = Entitlements.normalizeAppearance(parseAppearance(user?.appearance), entitlements);
|
||||
return {
|
||||
appearance,
|
||||
entitlements
|
||||
};
|
||||
}
|
||||
|
||||
async saveAppearanceForSocket(socket, input) {
|
||||
const user = await this.userForSocket(socket);
|
||||
const entitlements = await this.entitlementsForUser(user);
|
||||
const appearance = Entitlements.normalizeAppearance(input, entitlements);
|
||||
|
||||
if (!this.db || !user?.id) {
|
||||
return { appearance, entitlements };
|
||||
}
|
||||
|
||||
const result = await this.db.query(`
|
||||
UPDATE users
|
||||
SET appearance = $1::jsonb,
|
||||
updated_at = NOW()
|
||||
WHERE id = $2
|
||||
RETURNING *
|
||||
`, [JSON.stringify(appearance), user.id]);
|
||||
|
||||
const updated = result.rows && result.rows[0] ? result.rows[0] : { ...user, appearance };
|
||||
this._refreshSessionCache(socket.id, updated);
|
||||
return {
|
||||
appearance: Entitlements.normalizeAppearance(parseAppearance(updated.appearance), entitlements),
|
||||
entitlements
|
||||
};
|
||||
}
|
||||
|
||||
_refreshSessionCache(socketId, user) {
|
||||
if (!socketId || !user || !this.sessionManager?.sessions) return;
|
||||
if (this.sessionManager.sessions.has(socketId)) {
|
||||
this.sessionManager.sessions.set(socketId, user);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = IdentityService;
|
||||
@@ -72,9 +72,9 @@ class PaymentHandlers {
|
||||
}
|
||||
|
||||
try {
|
||||
const { type, packageId } = data;
|
||||
const { type, packageId, productId } = data;
|
||||
const paymentType = type || data.gameMode || 'single_game';
|
||||
const options = { packageId, reuseExisting: true };
|
||||
const options = { packageId, productId, reuseExisting: true };
|
||||
const paymentRequest = await this.gameModeManager.createPaymentRequest(socket.id, paymentType, options);
|
||||
const cryptoType = this.gameModeManager.cryptoType;
|
||||
|
||||
@@ -86,7 +86,9 @@ class PaymentHandlers {
|
||||
paymentRequest.address,
|
||||
paymentRequest.amount,
|
||||
cryptoType,
|
||||
paymentType === 'credits_package' ? 'Credits package' : 'Single game',
|
||||
paymentType === 'single_game'
|
||||
? 'Single game'
|
||||
: (paymentRequest.package?.label || (paymentType === 'credits_package' ? 'Credits package' : 'Product purchase')),
|
||||
this.gameModeManager.currencyDecimals
|
||||
);
|
||||
} catch (qrErr) {
|
||||
@@ -102,6 +104,8 @@ class PaymentHandlers {
|
||||
currency: cryptoType,
|
||||
cryptoType: cryptoType,
|
||||
package: paymentRequest.package,
|
||||
productId: paymentRequest.productId,
|
||||
grants: paymentRequest.grants,
|
||||
paymentType: paymentType,
|
||||
qr: qrDataUrl,
|
||||
reused: !!paymentRequest.reused
|
||||
@@ -196,6 +200,14 @@ class PaymentHandlers {
|
||||
amount = Number(primaryPackage?.price ?? this.gameModeManager.creditsPackagePrice);
|
||||
const credits = primaryPackage?.credits ?? this.gameModeManager.creditsPerGameCost * 10;
|
||||
description = `${credits} credit package`;
|
||||
} else if (paymentType === 'cosmetic_pack') {
|
||||
const product = this.gameModeManager.getCosmeticProduct(options.productId || options.packageId);
|
||||
if (!product) {
|
||||
this.broadcastManager.sendStatusUpdate(socket.id, 'error', 'Invalid product selection.');
|
||||
return;
|
||||
}
|
||||
amount = Number(product.price);
|
||||
description = product.label || product.id;
|
||||
} else {
|
||||
this.broadcastManager.sendStatusUpdate(socket.id, 'error', 'Invalid game mode configuration.');
|
||||
return;
|
||||
@@ -210,6 +222,7 @@ class PaymentHandlers {
|
||||
const paymentRequest = await this.gameModeManager.createPaymentRequest(socket.id, paymentType, {
|
||||
reuseExisting: true,
|
||||
packageId: options.packageId,
|
||||
productId: options.productId,
|
||||
userId: sessionUserId
|
||||
});
|
||||
const reused = !!paymentRequest.reused;
|
||||
@@ -243,6 +256,8 @@ class PaymentHandlers {
|
||||
amountFormatted: formattedAmount,
|
||||
humanAmount: formattedAmount,
|
||||
paymentType,
|
||||
productId: paymentRequest.productId,
|
||||
grants: paymentRequest.grants,
|
||||
gameMode,
|
||||
cryptoType,
|
||||
description,
|
||||
@@ -256,7 +271,10 @@ class PaymentHandlers {
|
||||
? '🔁 Existing payment request still pending. Use the details below to pay.'
|
||||
: `💳 PAYMENT REQUIRED (${description})`;
|
||||
|
||||
const statusBody = `\n\nAmount: ${formattedAmount} ${cryptoType}\nAddress: ${paymentRequest.address}\n\n⚠️ Send EXACTLY ${formattedAmount} ${cryptoType}.\n🔄 Added to queue once mempool seen.\n⏰ Expires in 30 minutes.`;
|
||||
const nextStep = paymentType === 'single_game'
|
||||
? '🔄 Added to queue once mempool seen.'
|
||||
: '🔄 Purchase applies after block confirmation.';
|
||||
const statusBody = `\n\nAmount: ${formattedAmount} ${cryptoType}\nAddress: ${paymentRequest.address}\n\n⚠️ Send EXACTLY ${formattedAmount} ${cryptoType}.\n${nextStep}\n⏰ Expires in 30 minutes.`;
|
||||
|
||||
this.broadcastManager.sendStatusUpdate(
|
||||
socket.id,
|
||||
@@ -291,17 +309,16 @@ class PaymentHandlers {
|
||||
if (this.mempoolNotified.has(paymentRequest.address)) return;
|
||||
this.mempoolNotified.set(paymentRequest.address, Date.now());
|
||||
|
||||
// Check payment type — credits_package should NOT queue for a game
|
||||
const mapping = this.socketPaymentMap.get(socket.id);
|
||||
const isCredits = mapping && mapping.paymentType === 'credits_package';
|
||||
const isGameEntry = !mapping || mapping.paymentType === 'single_game';
|
||||
|
||||
const detectMessage = isCredits
|
||||
? 'Payment detected in mempool! Awaiting block confirmation to add credits...'
|
||||
const detectMessage = !isGameEntry
|
||||
? 'Payment detected in mempool! Awaiting block confirmation to apply your purchase...'
|
||||
: 'Payment detected in mempool! Adding you to the game queue...';
|
||||
socket.emit('payment_detected', { paymentId: paymentRequest.id, message: detectMessage, amount: status.amount, confirmations: 0 });
|
||||
|
||||
// Only queue for single_game payments (credits just add balance, no game queue)
|
||||
if (!isCredits) {
|
||||
// Only queue for single_game payments. Product purchases just apply grants.
|
||||
if (isGameEntry) {
|
||||
const existingIdx = this.queueManager.getPlayerIndex(socket.id);
|
||||
if (existingIdx === -1) {
|
||||
// Try to get DB userId from session
|
||||
@@ -362,28 +379,38 @@ class PaymentHandlers {
|
||||
this.confirmedPayments.add(paymentRequest.id);
|
||||
this._confirmedTimestamps.set(paymentRequest.id, Date.now());
|
||||
|
||||
// Handle credits_package: add credits to user
|
||||
// Handle non-game products: add credits / cosmetic grants / premium tier.
|
||||
const mapping = this.socketPaymentMap.get(socket.id);
|
||||
if (mapping && mapping.paymentType === 'credits_package' && this.gameModeManager) {
|
||||
if (mapping && mapping.paymentType !== 'single_game' && this.gameModeManager) {
|
||||
try {
|
||||
// processCreditsPackageConfirmation now atomically checks status='pending'
|
||||
const creditsResult = await this.gameModeManager.processCreditsPackageConfirmation(
|
||||
// Product confirmation atomically checks status='pending' and applies grants.
|
||||
const creditsResult = await this.gameModeManager.processProductPaymentConfirmation(
|
||||
socket.id,
|
||||
paymentRequest.id,
|
||||
mapping.package,
|
||||
Math.round(status.amount || 0)
|
||||
);
|
||||
if (creditsResult.success) {
|
||||
socket.emit('credits_update', { balance: creditsResult.newBalance });
|
||||
socket.emit('credits_update', {
|
||||
balance: creditsResult.newBalance,
|
||||
totalCreditsPurchased: creditsResult.totalCreditsPurchased || 0,
|
||||
...(creditsResult.entitlements || {})
|
||||
});
|
||||
if (creditsResult.entitlements) {
|
||||
socket.emit('identity_update', { entitlements: creditsResult.entitlements });
|
||||
}
|
||||
const packs = creditsResult.grantsApplied?.packs || [];
|
||||
const packText = packs.length ? `\nUnlocked: ${packs.map(p => p.id).join(', ')}` : '';
|
||||
socket.emit('payment_confirmed', {
|
||||
paymentId: paymentRequest.id,
|
||||
message: `Payment confirmed! Added ${creditsResult.creditsAdded} credits. New balance: ${creditsResult.newBalance}`,
|
||||
message: `Payment confirmed! Added ${creditsResult.creditsAdded} credits. New balance: ${creditsResult.newBalance}${packText}`,
|
||||
creditsAdded: creditsResult.creditsAdded,
|
||||
newBalance: creditsResult.newBalance,
|
||||
grantsApplied: creditsResult.grantsApplied,
|
||||
confirmations: status.confirmations
|
||||
});
|
||||
this.broadcastManager.sendStatusUpdate(socket.id, 'success',
|
||||
`✅ CREDITS PURCHASED!\n\n+${creditsResult.creditsAdded} credits added.\nNew balance: ${creditsResult.newBalance} credits.\n\nType 'enter' to start a game!`);
|
||||
`✅ PURCHASE CONFIRMED!\n\n+${creditsResult.creditsAdded} credits added.\nNew balance: ${creditsResult.newBalance} credits.${packText}\n\nType 'enter' to start a game!`);
|
||||
} else if (creditsResult.alreadyProcessed) {
|
||||
// Payment was already confirmed (e.g., after server restart) - just notify user
|
||||
console.log(`[PaymentHandlers] Payment ${paymentRequest.id} already processed, skipping duplicate`);
|
||||
|
||||
@@ -16,6 +16,8 @@ const ConnectionHandler = require('./connectionHandler');
|
||||
const ChatHandler = require('./chatHandler');
|
||||
const QueueHandler = require('./queueHandler');
|
||||
const SpectatorManager = require('./spectatorManager');
|
||||
const TavernManager = require('./tavernManager');
|
||||
const IdentityService = require('./identityService');
|
||||
const SuspendedGameManager = require('./suspendedGameManager');
|
||||
const MemoryManager = require('../utils/memoryManager');
|
||||
const { normalizeError } = require('../utils/errors');
|
||||
@@ -39,6 +41,7 @@ class SocketHandlers {
|
||||
'game:queue': { window: 30000, max: 5 },
|
||||
'chat:message': { window: 10000, max: 12 },
|
||||
'address:set': { window: 300000, max: 3 },
|
||||
'identity:update': { window: 10000, max: 8 },
|
||||
'connection:new': { window: 60000, max: 10 }
|
||||
}
|
||||
});
|
||||
@@ -118,6 +121,13 @@ class SocketHandlers {
|
||||
sessionManager: this.sessionManager
|
||||
});
|
||||
|
||||
this.identityService = new IdentityService({
|
||||
db: this.gameModeManager?.db,
|
||||
gameModeManager: this.gameModeManager,
|
||||
sessionManager: this.sessionManager,
|
||||
debugManager: this.debugManager
|
||||
});
|
||||
|
||||
// Address / payout handling encapsulated in AddressManager
|
||||
this.addressManager = new AddressManager({
|
||||
gameModeManager: this.gameModeManager,
|
||||
@@ -180,6 +190,25 @@ class SocketHandlers {
|
||||
// Wire spectator manager to game manager (for game over notifications)
|
||||
this.gameManager.setSpectatorManager(this.spectatorManager);
|
||||
|
||||
// Initialize tavern manager (social hangout mode). Inert unless TAVERN_ENABLED=true.
|
||||
// Load the designed tavern room (imported .tmx); fall back to the procedural map if absent.
|
||||
let tavernRoomData = null;
|
||||
const tavernRoomUrl = 'assets/kenney/tavern_room.json';
|
||||
try {
|
||||
const roomPath = require('path').join(__dirname, '../../html', tavernRoomUrl);
|
||||
tavernRoomData = JSON.parse(require('fs').readFileSync(roomPath, 'utf8'));
|
||||
} catch (e) {
|
||||
if (this.debugManager.CONSOLE_LOGGING) console.log('Tavern room JSON not found; using default map:', e.message);
|
||||
}
|
||||
this.tavernManager = new TavernManager({
|
||||
io: this.io,
|
||||
debugManager: this.debugManager,
|
||||
roomData: tavernRoomData,
|
||||
roomUrl: tavernRoomData ? tavernRoomUrl : null,
|
||||
entitlementProvider: async (socket) => this._entitlementsForSocket(socket)
|
||||
});
|
||||
this.tavernManager.initialize();
|
||||
|
||||
// Initialize suspended game manager for reconnection support
|
||||
this.suspendedGameManager = new SuspendedGameManager({
|
||||
debugManager: this.debugManager,
|
||||
@@ -336,6 +365,9 @@ class SocketHandlers {
|
||||
if (this.gameModeManager) {
|
||||
socket.emit('game_mode_info', this.gameModeManager.getGameModeInfo());
|
||||
}
|
||||
this._emitIdentity(socket).catch(err => {
|
||||
if (this.debugManager?.CONSOLE_LOGGING) console.warn('Failed to send identity snapshot:', err.message);
|
||||
});
|
||||
|
||||
// Send chat history to new user
|
||||
if (this.chatHandler && typeof this.chatHandler.sendChatHistoryToUser === 'function') {
|
||||
@@ -374,11 +406,15 @@ class SocketHandlers {
|
||||
if (sessionUser) {
|
||||
socket.emit('credits_update', {
|
||||
balance: sessionUser.credits || 0,
|
||||
totalCreditsPurchased: sessionUser.total_credits_purchased || 0,
|
||||
creditsPerGame: this.gameModeManager?.creditsPerGameCost || 1
|
||||
});
|
||||
}
|
||||
} catch (e) { /* ignore — credits will update on next action */ }
|
||||
}
|
||||
this._emitIdentity(socket).catch(err => {
|
||||
if (this.debugManager?.CONSOLE_LOGGING) console.warn('Failed to re-send identity snapshot:', err.message);
|
||||
});
|
||||
});
|
||||
socket.on('auto_start', () => this.handleAutoStart(socket)); // New handler for start button
|
||||
socket.on('play_free', () => this.handleAutoStart(socket, { free: true })); // Explicit free-play choice
|
||||
@@ -391,11 +427,24 @@ class SocketHandlers {
|
||||
socket.on('check_payment_status', (data) => this.handleCheckPaymentStatus(socket, data));
|
||||
socket.on('get_user_credits', () => this.handleGetUserCredits(socket));
|
||||
socket.on('address:update', (data) => this.handleAddressUpdate(socket, data));
|
||||
socket.on('identity:get', () => this.handleIdentityGet(socket));
|
||||
socket.on('identity:update', (data) => this.handleIdentityUpdate(socket, data));
|
||||
|
||||
// Spectator handlers
|
||||
socket.on('get_active_games', (options) => this.handleGetActiveGames(socket, options));
|
||||
socket.on('spectate_game', (data) => this.handleSpectateGame(socket, data));
|
||||
socket.on('leave_spectate', () => this.handleLeaveSpectate(socket));
|
||||
|
||||
// Tavern handlers (social hangout mode; refused server-side unless enabled)
|
||||
socket.on('tavern_join', (data) => {
|
||||
Promise.resolve(this.tavernManager.join(socket, data)).catch(err => {
|
||||
console.error('Tavern join failed:', err.message);
|
||||
socket.emit('tavern_error', { message: 'Could not enter the tavern.' });
|
||||
});
|
||||
});
|
||||
socket.on('tavern_move', (data) => this.tavernManager.move(socket, data));
|
||||
socket.on('tavern_chat', (data) => this.tavernManager.chat(socket, data));
|
||||
socket.on('tavern_leave', () => this.tavernManager.leave(socket));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -497,7 +546,10 @@ class SocketHandlers {
|
||||
}
|
||||
// Emit credits_update if credits were spent
|
||||
if (startRes.creditsRemaining !== undefined) {
|
||||
this.io.to(socket.id).emit('credits_update', { balance: startRes.creditsRemaining });
|
||||
this.io.to(socket.id).emit('credits_update', {
|
||||
balance: startRes.creditsRemaining,
|
||||
totalCreditsPurchased: startRes.totalCreditsPurchased || 0
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -755,6 +807,11 @@ class SocketHandlers {
|
||||
this.spectatorManager.handleDisconnect(socketId);
|
||||
}
|
||||
|
||||
// Clean up tavern presence
|
||||
if (this.tavernManager) {
|
||||
this.tavernManager.handleDisconnect(socketId);
|
||||
}
|
||||
|
||||
// Evict the cached session row LAST (after the suspend logic above read it),
|
||||
// so the sessions map doesn't grow unbounded with every socket ever seen.
|
||||
if (this.sessionManager?.removeSocket) {
|
||||
@@ -763,6 +820,46 @@ class SocketHandlers {
|
||||
});
|
||||
}
|
||||
|
||||
async _emitIdentity(socket, extra = {}) {
|
||||
if (!this.identityService || !socket) return null;
|
||||
const snapshot = await this.identityService.identityForSocket(socket);
|
||||
socket.emit('identity_update', { ...snapshot, ...extra });
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
async _entitlementsForSocket(socket) {
|
||||
if (!this.identityService || !socket) return { premium: false, level: 'free', packs: {}, totalCreditsPurchased: 0 };
|
||||
return this.identityService.entitlementsForSocket(socket);
|
||||
}
|
||||
|
||||
async handleIdentityGet(socket) {
|
||||
try {
|
||||
await this._emitIdentity(socket);
|
||||
} catch (err) {
|
||||
socket.emit('identity_error', { message: 'Could not load character identity.' });
|
||||
}
|
||||
}
|
||||
|
||||
async handleIdentityUpdate(socket, data = {}) {
|
||||
try {
|
||||
const rlId = stableId(socket, this.sessionManager);
|
||||
const rlIp = clientIp(socket);
|
||||
const rateLimitResult = await this.rateLimiter.checkLimit(rlId, 'identity:update', rlIp);
|
||||
if (!rateLimitResult.allowed) {
|
||||
socket.emit('identity_error', { message: 'Character changes are temporarily rate limited.' });
|
||||
return;
|
||||
}
|
||||
await this.rateLimiter.recordAttempt(rlId, 'identity:update', rlIp);
|
||||
|
||||
const input = data && data.appearance ? data.appearance : data;
|
||||
const snapshot = await this.identityService.saveAppearanceForSocket(socket, input);
|
||||
socket.emit('identity_update', { ...snapshot, saved: true });
|
||||
} catch (err) {
|
||||
const normalized = normalizeError(err, 'Failed to update character identity');
|
||||
socket.emit('identity_error', { message: normalized.safeMessage || 'Could not save character identity.' });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle debug ping
|
||||
*/
|
||||
@@ -1082,7 +1179,8 @@ class SocketHandlers {
|
||||
chat: this.chatHandler.getStats(),
|
||||
games: this.gameManager.getStats(),
|
||||
queue: this.queueHandler.getStats(),
|
||||
spectators: this.spectatorManager ? this.spectatorManager.getStats() : null
|
||||
spectators: this.spectatorManager ? this.spectatorManager.getStats() : null,
|
||||
tavern: this.tavernManager ? this.tavernManager.getStats() : null
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1095,6 +1193,10 @@ class SocketHandlers {
|
||||
}
|
||||
|
||||
// Shutdown components in reverse order of initialization
|
||||
if (this.tavernManager) {
|
||||
this.tavernManager.shutdown();
|
||||
}
|
||||
|
||||
if (this.spectatorManager) {
|
||||
this.spectatorManager.shutdown();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,215 @@
|
||||
const Room = require('../multiplayer/Room');
|
||||
const Appearance = require('../multiplayer/appearance');
|
||||
const Entitlements = require('../multiplayer/entitlements');
|
||||
const SocketChatProvider = require('./chat/SocketChatProvider');
|
||||
|
||||
function escapeHtml(s) {
|
||||
return String(s)
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''');
|
||||
}
|
||||
|
||||
/**
|
||||
* TavernManager — transport and lifecycle for the Tavern mode.
|
||||
*
|
||||
* Owns a shared Room, a server-tick timer, and Socket.IO room broadcasts. Structured like
|
||||
* SpectatorManager. Disabled unless TAVERN_ENABLED=true: when disabled, no timer runs and
|
||||
* join requests are refused, so this is inert on instances that don't opt in.
|
||||
*
|
||||
* Movement is server-authoritative. Clients send a direction; the Room validates it. State
|
||||
* is broadcast to occupants once per server tick (clients render from these snapshots).
|
||||
*/
|
||||
class TavernManager {
|
||||
constructor({ io, debugManager, roomId = 'main', tickMs = null, roomData = null, roomUrl = null, entitlementProvider = null } = {}) {
|
||||
this.io = io;
|
||||
this.debugManager = debugManager;
|
||||
this.enabled = process.env.TAVERN_ENABLED === 'true';
|
||||
this.roomId = roomId;
|
||||
|
||||
// Snapshot broadcast cadence. Default 100ms (10 Hz); override with TAVERN_TICK_MS.
|
||||
const envTick = parseInt(process.env.TAVERN_TICK_MS, 10);
|
||||
this.tickMs = tickMs || (Number.isFinite(envTick) && envTick > 0 ? envTick : 100);
|
||||
|
||||
this.moveCooldownMs = 60; // per-occupant flood guard
|
||||
this._lastMoveAt = new Map(); // socketId -> timestamp
|
||||
this.chatCooldownMs = 900; // per-occupant chat flood guard
|
||||
this._lastChatAt = new Map(); // socketId -> timestamp
|
||||
this._tickInterval = null;
|
||||
this.entitlementProvider = entitlementProvider;
|
||||
|
||||
this.room = new Room({ id: this.roomId, type: 'tavern', roomData: roomData, roomUrl: roomUrl });
|
||||
|
||||
// Tavern chat is ephemeral (no history) and delivered only to the tavern room, via the
|
||||
// same ChatProvider seam the global chat uses.
|
||||
this.chatProvider = new SocketChatProvider({ io: this.io, debugManager: this.debugManager });
|
||||
}
|
||||
|
||||
get channel() {
|
||||
return `tavern:${this.roomId}`;
|
||||
}
|
||||
|
||||
/** Start the server tick. No-op (and no timer) unless enabled. */
|
||||
initialize() {
|
||||
if (!this.enabled) return;
|
||||
this._tickInterval = setInterval(() => this._tick(), this.tickMs);
|
||||
if (this.debugManager?.CONSOLE_LOGGING) {
|
||||
console.log(`Tavern enabled (room '${this.roomId}', tick ${this.tickMs}ms)`);
|
||||
}
|
||||
}
|
||||
|
||||
_tick() {
|
||||
this.room.tick();
|
||||
if (this.room.size > 0) {
|
||||
this.io.to(this.channel).emit('tavern_update', this.room.snapshot());
|
||||
}
|
||||
}
|
||||
|
||||
_sanitizeName(name) {
|
||||
if (typeof name !== 'string') return null;
|
||||
// Keep letters/numbers/space and a few separators; cap length.
|
||||
const cleaned = name.replace(/[^\p{L}\p{N} _.-]/gu, '').trim().slice(0, 16);
|
||||
return cleaned.length ? cleaned : null;
|
||||
}
|
||||
|
||||
_validateAvatar(avatar) {
|
||||
return Appearance.isValidAvatar(avatar) ? avatar : 'default';
|
||||
}
|
||||
|
||||
async _entitlementsFor(socket) {
|
||||
if (typeof this.entitlementProvider !== 'function') return { premium: false, totalCreditsPurchased: 0 };
|
||||
try {
|
||||
return await this.entitlementProvider(socket);
|
||||
} catch (_) {
|
||||
return { premium: false, totalCreditsPurchased: 0 };
|
||||
}
|
||||
}
|
||||
|
||||
_normalizeAppearance(data = {}, entitlements = {}) {
|
||||
const raw = data.appearance || { avatar: data.avatar };
|
||||
return Entitlements.normalizeAppearance(raw, entitlements);
|
||||
}
|
||||
|
||||
_normalizeDir(data) {
|
||||
if (data && typeof data.dir === 'string') {
|
||||
switch (data.dir) {
|
||||
case 'up': return { dx: 0, dy: -1 };
|
||||
case 'down': return { dx: 0, dy: 1 };
|
||||
case 'left': return { dx: -1, dy: 0 };
|
||||
case 'right': return { dx: 1, dy: 0 };
|
||||
default: return { dx: 0, dy: 0 };
|
||||
}
|
||||
}
|
||||
return {
|
||||
dx: Math.sign(Number(data && data.dx) || 0),
|
||||
dy: Math.sign(Number(data && data.dy) || 0)
|
||||
};
|
||||
}
|
||||
|
||||
async join(socket, data = {}) {
|
||||
if (!this.enabled) {
|
||||
socket.emit('tavern_error', { message: 'Tavern is not enabled on this server.' });
|
||||
return { success: false };
|
||||
}
|
||||
const name = this._sanitizeName(data.name);
|
||||
const entitlements = await this._entitlementsFor(socket);
|
||||
const appearance = this._normalizeAppearance(data, entitlements);
|
||||
const avatar = appearance.avatar;
|
||||
const occ = this.room.addOccupant(socket.id, { name, avatar, appearance });
|
||||
if (!occ) {
|
||||
socket.emit('tavern_error', { message: 'The tavern is full.' });
|
||||
return { success: false };
|
||||
}
|
||||
socket.join(this.channel);
|
||||
// Full state (map + occupants) to the joiner; the next tick shows the arrival to others.
|
||||
socket.emit('tavern_joined', { you: socket.id, state: this.room.fullState() });
|
||||
if (this.debugManager?.CONSOLE_LOGGING) {
|
||||
console.log(`[Tavern] +${String(socket.id).slice(0, 6)} (${this.room.size} present)`);
|
||||
}
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
move(socket, data = {}) {
|
||||
if (!this.enabled) return;
|
||||
if (!this.room.getOccupant(socket.id)) return;
|
||||
|
||||
const now = Date.now();
|
||||
if (now - (this._lastMoveAt.get(socket.id) || 0) < this.moveCooldownMs) return;
|
||||
this._lastMoveAt.set(socket.id, now);
|
||||
|
||||
const { dx, dy } = this._normalizeDir(data);
|
||||
if (dx === 0 && dy === 0) return;
|
||||
this.room.moveOccupant(socket.id, dx, dy); // next tick broadcasts the result
|
||||
}
|
||||
|
||||
chat(socket, data = {}) {
|
||||
if (!this.enabled) return;
|
||||
const occ = this.room.getOccupant(socket.id);
|
||||
if (!occ) return; // must be in the tavern to talk
|
||||
|
||||
let text = (data && typeof data.text === 'string') ? data.text.trim() : '';
|
||||
if (!text) return;
|
||||
if (text.length > TavernManager.MAX_CHAT_LENGTH) text = text.slice(0, TavernManager.MAX_CHAT_LENGTH);
|
||||
|
||||
const now = Date.now();
|
||||
if (now - (this._lastChatAt.get(socket.id) || 0) < this.chatCooldownMs) {
|
||||
// Tell the sender instead of silently dropping — a silent drop with a cleared
|
||||
// input reads as "my message disappeared".
|
||||
if (socket && typeof socket.emit === 'function') {
|
||||
socket.emit('tavern_notice', { message: 'Easy — wait a moment before your next message.' });
|
||||
}
|
||||
return;
|
||||
}
|
||||
this._lastChatAt.set(socket.id, now);
|
||||
|
||||
const username = occ.name || String(socket.id).slice(0, 6);
|
||||
// Escape here (delivery is trusted-escaped, rendered as HTML on the client).
|
||||
this.chatProvider.publish({
|
||||
scope: this.channel,
|
||||
username,
|
||||
text: escapeHtml(text),
|
||||
ts: now,
|
||||
socketId: socket.id
|
||||
});
|
||||
}
|
||||
|
||||
leave(socket) {
|
||||
this.handleDisconnect(socket.id, socket);
|
||||
}
|
||||
|
||||
handleDisconnect(socketId, socket = null) {
|
||||
const existed = this.room.removeOccupant(socketId);
|
||||
this._lastMoveAt.delete(socketId);
|
||||
this._lastChatAt.delete(socketId);
|
||||
if (existed) {
|
||||
const sock = socket || (this.io.sockets?.sockets?.get?.(socketId));
|
||||
if (sock) sock.leave(this.channel);
|
||||
if (this.debugManager?.CONSOLE_LOGGING) {
|
||||
console.log(`[Tavern] -${String(socketId).slice(0, 6)} (${this.room.size} present)`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
getStats() {
|
||||
return { enabled: this.enabled, roomId: this.roomId, occupants: this.room.size };
|
||||
}
|
||||
|
||||
shutdown() {
|
||||
if (this._tickInterval) {
|
||||
clearInterval(this._tickInterval);
|
||||
this._tickInterval = null;
|
||||
}
|
||||
this._lastMoveAt.clear();
|
||||
this._lastChatAt.clear();
|
||||
}
|
||||
}
|
||||
|
||||
// Cosmetic avatar ids the server will accept. Availability/unlocks are enforced via
|
||||
// the Entitlements policy during join.
|
||||
TavernManager.AVATARS = Appearance.avatarIds();
|
||||
TavernManager.PREMIUM_AVATARS = Appearance.premiumAvatarIds();
|
||||
TavernManager.MAX_CHAT_LENGTH = 200;
|
||||
|
||||
module.exports = TavernManager;
|
||||
Generated
+396
-52
@@ -7,20 +7,23 @@
|
||||
"": {
|
||||
"name": "wownerogue",
|
||||
"version": "1.0.0",
|
||||
"license": "ISC",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"axios": "^1.9.0",
|
||||
"dotenv": "^16.0.3",
|
||||
"express": "^4.17.1",
|
||||
"express": "^4.21.3",
|
||||
"node-pg-migrate": "^8.0.4",
|
||||
"pg": "^8.15.5",
|
||||
"qrcode": "^1.5.3",
|
||||
"resend": "^4.0.0",
|
||||
"socket.io": "^4.8.1",
|
||||
"socket.io-client": "^4.8.1",
|
||||
"tweetnacl": "^1.0.3",
|
||||
"uuid": "^9.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"jest": "^29.7.0"
|
||||
"jest": "^29.7.0",
|
||||
"playwright-core": "^1.61.1"
|
||||
}
|
||||
},
|
||||
"node_modules/@babel/code-frame": {
|
||||
@@ -1010,6 +1013,37 @@
|
||||
"@jridgewell/sourcemap-codec": "^1.4.14"
|
||||
}
|
||||
},
|
||||
"node_modules/@react-email/render": {
|
||||
"version": "1.1.2",
|
||||
"resolved": "https://registry.npmjs.org/@react-email/render/-/render-1.1.2.tgz",
|
||||
"integrity": "sha512-RnRehYN3v9gVlNMehHPHhyp2RQo7+pSkHDtXPvg3s0GbzM9SQMW4Qrf8GRNvtpLC4gsI+Wt0VatNRUFqjvevbw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"html-to-text": "^9.0.5",
|
||||
"prettier": "^3.5.3",
|
||||
"react-promise-suspense": "^0.3.4"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18.0.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": "^18.0 || ^19.0 || ^19.0.0-rc",
|
||||
"react-dom": "^18.0 || ^19.0 || ^19.0.0-rc"
|
||||
}
|
||||
},
|
||||
"node_modules/@selderee/plugin-htmlparser2": {
|
||||
"version": "0.11.0",
|
||||
"resolved": "https://registry.npmjs.org/@selderee/plugin-htmlparser2/-/plugin-htmlparser2-0.11.0.tgz",
|
||||
"integrity": "sha512-P33hHGdldxGabLFjPPpaTxVolMrzrcegejx+0GxjrIb9Zv48D8yAIA/QTDR2dFl7Uz7urX8aX6+5bCZslr+gWQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"domhandler": "^5.0.3",
|
||||
"selderee": "^0.11.0"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://ko-fi.com/killymxi"
|
||||
}
|
||||
},
|
||||
"node_modules/@sinclair/typebox": {
|
||||
"version": "0.27.8",
|
||||
"resolved": "https://registry.npmjs.org/@sinclair/typebox/-/typebox-0.27.8.tgz",
|
||||
@@ -1379,28 +1413,58 @@
|
||||
}
|
||||
},
|
||||
"node_modules/body-parser": {
|
||||
"version": "1.20.3",
|
||||
"resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.3.tgz",
|
||||
"integrity": "sha512-7rAxByjUMqQ3/bHJy7D6OGXvx/MMc4IqBn/X0fcM1QUcAItpZrBEYhWGem+tzXH90c+G01ypMcYJBO9Y30203g==",
|
||||
"version": "1.20.5",
|
||||
"resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.5.tgz",
|
||||
"integrity": "sha512-3grm+/2tUOvu2cjJkvsIxrv/wVpfXQW4PsQHYm7yk4vfpu7Ekl6nEsYBoJUL6qDwZUx8wUhQ8tR2qz+ad9c9OA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"bytes": "3.1.2",
|
||||
"bytes": "~3.1.2",
|
||||
"content-type": "~1.0.5",
|
||||
"debug": "2.6.9",
|
||||
"depd": "2.0.0",
|
||||
"destroy": "1.2.0",
|
||||
"http-errors": "2.0.0",
|
||||
"iconv-lite": "0.4.24",
|
||||
"on-finished": "2.4.1",
|
||||
"qs": "6.13.0",
|
||||
"raw-body": "2.5.2",
|
||||
"destroy": "~1.2.0",
|
||||
"http-errors": "~2.0.1",
|
||||
"iconv-lite": "~0.4.24",
|
||||
"on-finished": "~2.4.1",
|
||||
"qs": "~6.15.1",
|
||||
"raw-body": "~2.5.3",
|
||||
"type-is": "~1.6.18",
|
||||
"unpipe": "1.0.0"
|
||||
"unpipe": "~1.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.8",
|
||||
"npm": "1.2.8000 || >= 1.4.16"
|
||||
}
|
||||
},
|
||||
"node_modules/body-parser/node_modules/http-errors": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz",
|
||||
"integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"depd": "~2.0.0",
|
||||
"inherits": "~2.0.4",
|
||||
"setprototypeof": "~1.2.0",
|
||||
"statuses": "~2.0.2",
|
||||
"toidentifier": "~1.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.8"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/express"
|
||||
}
|
||||
},
|
||||
"node_modules/body-parser/node_modules/statuses": {
|
||||
"version": "2.0.2",
|
||||
"resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz",
|
||||
"integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/braces": {
|
||||
"version": "3.0.3",
|
||||
"resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz",
|
||||
@@ -1465,6 +1529,7 @@
|
||||
"version": "3.1.2",
|
||||
"resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz",
|
||||
"integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.8"
|
||||
}
|
||||
@@ -1485,6 +1550,7 @@
|
||||
"version": "1.0.4",
|
||||
"resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz",
|
||||
"integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"call-bind-apply-helpers": "^1.0.2",
|
||||
"get-intrinsic": "^1.3.0"
|
||||
@@ -1739,6 +1805,7 @@
|
||||
"version": "1.0.5",
|
||||
"resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz",
|
||||
"integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.6"
|
||||
}
|
||||
@@ -1842,7 +1909,6 @@
|
||||
"version": "4.3.1",
|
||||
"resolved": "https://registry.npmjs.org/deepmerge/-/deepmerge-4.3.1.tgz",
|
||||
"integrity": "sha512-3sUqbMEc77XqpdNO7FRyRog+eW3ph+GYCbj+rK+uYyRMuwsVy0rMiVtPn+QJlKFvWP/1PYpapqYn0Me2knFn+A==",
|
||||
"dev": true,
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
@@ -1896,6 +1962,61 @@
|
||||
"resolved": "https://registry.npmjs.org/dijkstrajs/-/dijkstrajs-1.0.3.tgz",
|
||||
"integrity": "sha512-qiSlmBq9+BCdCA/L46dw8Uy93mloxsPSbwnm5yrKn2vMPiy8KyAskTF6zuV/j5BMsmOGZDPs7KjU+mjb670kfA=="
|
||||
},
|
||||
"node_modules/dom-serializer": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-2.0.0.tgz",
|
||||
"integrity": "sha512-wIkAryiqt/nV5EQKqQpo3SToSOV9J0DnbJqwK7Wv/Trc92zIAYZ4FlMu+JPFW1DfGFt81ZTCGgDEabffXeLyJg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"domelementtype": "^2.3.0",
|
||||
"domhandler": "^5.0.2",
|
||||
"entities": "^4.2.0"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/cheeriojs/dom-serializer?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/domelementtype": {
|
||||
"version": "2.3.0",
|
||||
"resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-2.3.0.tgz",
|
||||
"integrity": "sha512-OLETBj6w0OsagBwdXnPdN0cnMfF9opN69co+7ZrbfPGrdpPVNBUj02spi6B1N7wChLQiPn4CSH/zJvXw56gmHw==",
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/fb55"
|
||||
}
|
||||
],
|
||||
"license": "BSD-2-Clause"
|
||||
},
|
||||
"node_modules/domhandler": {
|
||||
"version": "5.0.3",
|
||||
"resolved": "https://registry.npmjs.org/domhandler/-/domhandler-5.0.3.tgz",
|
||||
"integrity": "sha512-cgwlv/1iFQiFnU96XXgROh8xTeetsnJiDsTc7TYCLFd9+/WNkIqPTxiM/8pSd8VIrhXGTf1Ny1q1hquVqDJB5w==",
|
||||
"license": "BSD-2-Clause",
|
||||
"dependencies": {
|
||||
"domelementtype": "^2.3.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 4"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/fb55/domhandler?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/domutils": {
|
||||
"version": "3.2.2",
|
||||
"resolved": "https://registry.npmjs.org/domutils/-/domutils-3.2.2.tgz",
|
||||
"integrity": "sha512-6kZKyUajlDuqlHKVX1w7gyslj9MPIXzIFiz/rGu35uC1wMi+kMhQwGhl4lt9unC9Vb9INnY9Z3/ZA3+FhASLaw==",
|
||||
"license": "BSD-2-Clause",
|
||||
"dependencies": {
|
||||
"dom-serializer": "^2.0.0",
|
||||
"domelementtype": "^2.3.0",
|
||||
"domhandler": "^5.0.3"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/fb55/domutils?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/dotenv": {
|
||||
"version": "16.5.0",
|
||||
"resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.5.0.tgz",
|
||||
@@ -2052,6 +2173,18 @@
|
||||
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
|
||||
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="
|
||||
},
|
||||
"node_modules/entities": {
|
||||
"version": "4.5.0",
|
||||
"resolved": "https://registry.npmjs.org/entities/-/entities-4.5.0.tgz",
|
||||
"integrity": "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==",
|
||||
"license": "BSD-2-Clause",
|
||||
"engines": {
|
||||
"node": ">=0.12"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/fb55/entities?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/error-ex": {
|
||||
"version": "1.3.4",
|
||||
"resolved": "https://registry.npmjs.org/error-ex/-/error-ex-1.3.4.tgz",
|
||||
@@ -2201,38 +2334,39 @@
|
||||
}
|
||||
},
|
||||
"node_modules/express": {
|
||||
"version": "4.21.2",
|
||||
"resolved": "https://registry.npmjs.org/express/-/express-4.21.2.tgz",
|
||||
"integrity": "sha512-28HqgMZAmih1Czt9ny7qr6ek2qddF4FclbMzwhCREB6OFfH+rXAnuNCwo1/wFvrtbgsQDb4kSbX9de9lFbrXnA==",
|
||||
"version": "4.22.2",
|
||||
"resolved": "https://registry.npmjs.org/express/-/express-4.22.2.tgz",
|
||||
"integrity": "sha512-IuL+Elrou2ZvCFHs18/CIzy2Nzvo25nZ1/D2eIZlz7c+QUayAcYoiM2BthCjs+EBHVpjYjcuLDAiCWgeIX3X1Q==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"accepts": "~1.3.8",
|
||||
"array-flatten": "1.1.1",
|
||||
"body-parser": "1.20.3",
|
||||
"content-disposition": "0.5.4",
|
||||
"body-parser": "~1.20.5",
|
||||
"content-disposition": "~0.5.4",
|
||||
"content-type": "~1.0.4",
|
||||
"cookie": "0.7.1",
|
||||
"cookie-signature": "1.0.6",
|
||||
"cookie": "~0.7.1",
|
||||
"cookie-signature": "~1.0.6",
|
||||
"debug": "2.6.9",
|
||||
"depd": "2.0.0",
|
||||
"encodeurl": "~2.0.0",
|
||||
"escape-html": "~1.0.3",
|
||||
"etag": "~1.8.1",
|
||||
"finalhandler": "1.3.1",
|
||||
"fresh": "0.5.2",
|
||||
"http-errors": "2.0.0",
|
||||
"finalhandler": "~1.3.1",
|
||||
"fresh": "~0.5.2",
|
||||
"http-errors": "~2.0.0",
|
||||
"merge-descriptors": "1.0.3",
|
||||
"methods": "~1.1.2",
|
||||
"on-finished": "2.4.1",
|
||||
"on-finished": "~2.4.1",
|
||||
"parseurl": "~1.3.3",
|
||||
"path-to-regexp": "0.1.12",
|
||||
"path-to-regexp": "~0.1.12",
|
||||
"proxy-addr": "~2.0.7",
|
||||
"qs": "6.13.0",
|
||||
"qs": "~6.15.1",
|
||||
"range-parser": "~1.2.1",
|
||||
"safe-buffer": "5.2.1",
|
||||
"send": "0.19.0",
|
||||
"serve-static": "1.16.2",
|
||||
"send": "~0.19.0",
|
||||
"serve-static": "~1.16.2",
|
||||
"setprototypeof": "1.2.0",
|
||||
"statuses": "2.0.1",
|
||||
"statuses": "~2.0.1",
|
||||
"type-is": "~1.6.18",
|
||||
"utils-merge": "1.0.1",
|
||||
"vary": "~1.1.2"
|
||||
@@ -2245,6 +2379,12 @@
|
||||
"url": "https://opencollective.com/express"
|
||||
}
|
||||
},
|
||||
"node_modules/fast-deep-equal": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-2.0.1.tgz",
|
||||
"integrity": "sha512-bCK/2Z4zLidyB4ReuIsvALH6w31YfAQDmXMqMx6FyfHqvBxtjC0eRumeSu4Bs3XtXwpyIywtSTrVT99BxY1f9w==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/fast-json-stable-stringify": {
|
||||
"version": "2.1.0",
|
||||
"resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz",
|
||||
@@ -2561,6 +2701,41 @@
|
||||
"integrity": "sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==",
|
||||
"dev": true
|
||||
},
|
||||
"node_modules/html-to-text": {
|
||||
"version": "9.0.5",
|
||||
"resolved": "https://registry.npmjs.org/html-to-text/-/html-to-text-9.0.5.tgz",
|
||||
"integrity": "sha512-qY60FjREgVZL03vJU6IfMV4GDjGBIoOyvuFdpBDIX9yTlDw0TjxVBQp+P8NvpdIXNJvfWBTNul7fsAQJq2FNpg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@selderee/plugin-htmlparser2": "^0.11.0",
|
||||
"deepmerge": "^4.3.1",
|
||||
"dom-serializer": "^2.0.0",
|
||||
"htmlparser2": "^8.0.2",
|
||||
"selderee": "^0.11.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14"
|
||||
}
|
||||
},
|
||||
"node_modules/htmlparser2": {
|
||||
"version": "8.0.2",
|
||||
"resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-8.0.2.tgz",
|
||||
"integrity": "sha512-GYdjWKDkbRLkZ5geuHs5NY1puJ+PXwP7+fHPRz06Eirsb9ugf6d8kkXav6ADhcODhFFPMIXyxkxSuMf3D6NCFA==",
|
||||
"funding": [
|
||||
"https://github.com/fb55/htmlparser2?sponsor=1",
|
||||
{
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/fb55"
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"domelementtype": "^2.3.0",
|
||||
"domhandler": "^5.0.3",
|
||||
"domutils": "^3.0.1",
|
||||
"entities": "^4.4.0"
|
||||
}
|
||||
},
|
||||
"node_modules/http-errors": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.0.tgz",
|
||||
@@ -2589,6 +2764,7 @@
|
||||
"version": "0.4.24",
|
||||
"resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz",
|
||||
"integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"safer-buffer": ">= 2.1.2 < 3"
|
||||
},
|
||||
@@ -3585,6 +3761,15 @@
|
||||
"node": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/leac": {
|
||||
"version": "0.6.0",
|
||||
"resolved": "https://registry.npmjs.org/leac/-/leac-0.6.0.tgz",
|
||||
"integrity": "sha512-y+SqErxb8h7nE/fiEX07jsbuhrpO9lL8eca7/Y1nuWV2moNlXhyd59iDGcRf6moVyDMbmTNzL40SUyrFU/yDpg==",
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"url": "https://ko-fi.com/killymxi"
|
||||
}
|
||||
},
|
||||
"node_modules/leven": {
|
||||
"version": "3.1.0",
|
||||
"resolved": "https://registry.npmjs.org/leven/-/leven-3.1.0.tgz",
|
||||
@@ -3668,6 +3853,7 @@
|
||||
"version": "0.3.0",
|
||||
"resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz",
|
||||
"integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.6"
|
||||
}
|
||||
@@ -3859,6 +4045,7 @@
|
||||
"version": "1.13.4",
|
||||
"resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz",
|
||||
"integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
},
|
||||
@@ -3958,6 +4145,19 @@
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/parseley": {
|
||||
"version": "0.12.1",
|
||||
"resolved": "https://registry.npmjs.org/parseley/-/parseley-0.12.1.tgz",
|
||||
"integrity": "sha512-e6qHKe3a9HWr0oMRVDTRhKce+bRO8VGQR3NyVwcjwrbhMmFCX9KszEV35+rn4AdilFAq9VPxP/Fe1wC9Qjd2lw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"leac": "^0.6.0",
|
||||
"peberminta": "^0.9.0"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://ko-fi.com/killymxi"
|
||||
}
|
||||
},
|
||||
"node_modules/parseurl": {
|
||||
"version": "1.3.3",
|
||||
"resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz",
|
||||
@@ -4018,6 +4218,15 @@
|
||||
"resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.12.tgz",
|
||||
"integrity": "sha512-RA1GjUVMnvYFxuqovrEqZoxxW5NUZqbwKtYz/Tt7nXerk0LbLblQmrsgdeOxV5SFHf0UDggjS/bSeOZwt1pmEQ=="
|
||||
},
|
||||
"node_modules/peberminta": {
|
||||
"version": "0.9.0",
|
||||
"resolved": "https://registry.npmjs.org/peberminta/-/peberminta-0.9.0.tgz",
|
||||
"integrity": "sha512-XIxfHpEuSJbITd1H3EeQwpcZbTLHc+VVr8ANI9t5sit565tsI4/xK3KWTUFE2e6QiangUkh3B0jihzmGnNrRsQ==",
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"url": "https://ko-fi.com/killymxi"
|
||||
}
|
||||
},
|
||||
"node_modules/pg": {
|
||||
"version": "8.16.0",
|
||||
"resolved": "https://registry.npmjs.org/pg/-/pg-8.16.0.tgz",
|
||||
@@ -4138,6 +4347,19 @@
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/playwright-core": {
|
||||
"version": "1.61.1",
|
||||
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.61.1.tgz",
|
||||
"integrity": "sha512-h7Qlt6m4REp25qvIdvbDtVmD4LqVXfpRxhORv9L0jzETM05p4fuPJ3dKyuSXQxDSbXnmS79HAgi9589lGSpLkg==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"bin": {
|
||||
"playwright-core": "cli.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/pngjs": {
|
||||
"version": "5.0.0",
|
||||
"resolved": "https://registry.npmjs.org/pngjs/-/pngjs-5.0.0.tgz",
|
||||
@@ -4181,6 +4403,21 @@
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/prettier": {
|
||||
"version": "3.9.4",
|
||||
"resolved": "https://registry.npmjs.org/prettier/-/prettier-3.9.4.tgz",
|
||||
"integrity": "sha512-yWG/o/4oJfo036EKAfK6ACAoDOfHeRHx4tuxkfBZiauURiaSmYwlpOr5LQqKtIkRD2z1PLteme2WoxEnj4tHTg==",
|
||||
"license": "MIT",
|
||||
"bin": {
|
||||
"prettier": "bin/prettier.cjs"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/prettier/prettier?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/pretty-format": {
|
||||
"version": "29.7.0",
|
||||
"resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-29.7.0.tgz",
|
||||
@@ -4382,11 +4619,13 @@
|
||||
}
|
||||
},
|
||||
"node_modules/qs": {
|
||||
"version": "6.13.0",
|
||||
"resolved": "https://registry.npmjs.org/qs/-/qs-6.13.0.tgz",
|
||||
"integrity": "sha512-+38qI9SOr8tfZ4QmJNplMUxqjbe7LKvvZgWdExBOmd+egZTtjLB67Gu0HRX3u/XOq7UU2Nx6nsjvS16Z9uwfpg==",
|
||||
"version": "6.15.3",
|
||||
"resolved": "https://registry.npmjs.org/qs/-/qs-6.15.3.tgz",
|
||||
"integrity": "sha512-O9gl3zCl5h5blw1KGUzQKhA5oUXSl8rwUIM5o0S3nCXMliSvy5Dzx7/DJcI+SwgICv+IneSZwhBh1oSyEHA71A==",
|
||||
"license": "BSD-3-Clause",
|
||||
"dependencies": {
|
||||
"side-channel": "^1.0.6"
|
||||
"es-define-property": "^1.0.1",
|
||||
"side-channel": "^1.1.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=0.6"
|
||||
@@ -4404,25 +4643,87 @@
|
||||
}
|
||||
},
|
||||
"node_modules/raw-body": {
|
||||
"version": "2.5.2",
|
||||
"resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.2.tgz",
|
||||
"integrity": "sha512-8zGqypfENjCIqGhgXToC8aB2r7YrBX+AQAfIPs/Mlk+BtPTztOvTS01NRW/3Eh60J+a48lt8qsCzirQ6loCVfA==",
|
||||
"version": "2.5.3",
|
||||
"resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.3.tgz",
|
||||
"integrity": "sha512-s4VSOf6yN0rvbRZGxs8Om5CWj6seneMwK3oDb4lWDH0UPhWcxwOWw5+qk24bxq87szX1ydrwylIOp2uG1ojUpA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"bytes": "3.1.2",
|
||||
"http-errors": "2.0.0",
|
||||
"iconv-lite": "0.4.24",
|
||||
"unpipe": "1.0.0"
|
||||
"bytes": "~3.1.2",
|
||||
"http-errors": "~2.0.1",
|
||||
"iconv-lite": "~0.4.24",
|
||||
"unpipe": "~1.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/raw-body/node_modules/http-errors": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz",
|
||||
"integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"depd": "~2.0.0",
|
||||
"inherits": "~2.0.4",
|
||||
"setprototypeof": "~1.2.0",
|
||||
"statuses": "~2.0.2",
|
||||
"toidentifier": "~1.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.8"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/express"
|
||||
}
|
||||
},
|
||||
"node_modules/raw-body/node_modules/statuses": {
|
||||
"version": "2.0.2",
|
||||
"resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz",
|
||||
"integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/react": {
|
||||
"version": "19.2.7",
|
||||
"resolved": "https://registry.npmjs.org/react/-/react-19.2.7.tgz",
|
||||
"integrity": "sha512-HNe9WslTbXmFK8o8cmwgAeJFSBvt1bPdHCVKtaaV+WlAN36mpT4hcRpwbf3fY56ar2oIXzsBpOAiIRHAdY0OlQ==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/react-dom": {
|
||||
"version": "19.2.7",
|
||||
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.2.7.tgz",
|
||||
"integrity": "sha512-t0BRVXvbiE/o20Hfw669rLbMCDWtYZLvmJigy2f0MxsXF+71pxhR3xOkspmsO8h3ZlNzyibAmtCa3l4lYKk6gQ==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"scheduler": "^0.27.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": "^19.2.7"
|
||||
}
|
||||
},
|
||||
"node_modules/react-is": {
|
||||
"version": "18.3.1",
|
||||
"resolved": "https://registry.npmjs.org/react-is/-/react-is-18.3.1.tgz",
|
||||
"integrity": "sha512-/LLMVyas0ljjAtoYiPqYiL8VWXzUUdThrmU5+n20DZv+a+ClRoevUzw5JxU+Ieh5/c87ytoTBV9G1FiKfNJdmg==",
|
||||
"dev": true
|
||||
},
|
||||
"node_modules/react-promise-suspense": {
|
||||
"version": "0.3.4",
|
||||
"resolved": "https://registry.npmjs.org/react-promise-suspense/-/react-promise-suspense-0.3.4.tgz",
|
||||
"integrity": "sha512-I42jl7L3Ze6kZaq+7zXWSunBa3b1on5yfvUW6Eo/3fFOj6dZ5Bqmcd264nJbTK/gn1HjjILAjSwnZbV4RpSaNQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"fast-deep-equal": "^2.0.1"
|
||||
}
|
||||
},
|
||||
"node_modules/require-directory": {
|
||||
"version": "2.1.1",
|
||||
"resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz",
|
||||
@@ -4436,6 +4737,18 @@
|
||||
"resolved": "https://registry.npmjs.org/require-main-filename/-/require-main-filename-2.0.0.tgz",
|
||||
"integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg=="
|
||||
},
|
||||
"node_modules/resend": {
|
||||
"version": "4.8.0",
|
||||
"resolved": "https://registry.npmjs.org/resend/-/resend-4.8.0.tgz",
|
||||
"integrity": "sha512-R8eBOFQDO6dzRTDmaMEdpqrkmgSjPpVXt4nGfWsZdYOet0kqra0xgbvTES6HmCriZEXbmGk3e0DiGIaLFTFSHA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@react-email/render": "1.1.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/resolve": {
|
||||
"version": "1.22.10",
|
||||
"resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.10.tgz",
|
||||
@@ -4508,7 +4821,27 @@
|
||||
"node_modules/safer-buffer": {
|
||||
"version": "2.1.2",
|
||||
"resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
|
||||
"integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg=="
|
||||
"integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/scheduler": {
|
||||
"version": "0.27.0",
|
||||
"resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.27.0.tgz",
|
||||
"integrity": "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q==",
|
||||
"license": "MIT",
|
||||
"peer": true
|
||||
},
|
||||
"node_modules/selderee": {
|
||||
"version": "0.11.0",
|
||||
"resolved": "https://registry.npmjs.org/selderee/-/selderee-0.11.0.tgz",
|
||||
"integrity": "sha512-5TF+l7p4+OsnP8BCCvSyZiSPc4x4//p5uPwK8TCnVPJYRmU2aYKMpOXvw8zM5a5JvuuCGN1jmsMwuU2W02ukfA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"parseley": "^0.12.0"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://ko-fi.com/killymxi"
|
||||
}
|
||||
},
|
||||
"node_modules/semver": {
|
||||
"version": "6.3.1",
|
||||
@@ -4599,13 +4932,14 @@
|
||||
}
|
||||
},
|
||||
"node_modules/side-channel": {
|
||||
"version": "1.1.0",
|
||||
"resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz",
|
||||
"integrity": "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==",
|
||||
"version": "1.1.1",
|
||||
"resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.1.tgz",
|
||||
"integrity": "sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"es-errors": "^1.3.0",
|
||||
"object-inspect": "^1.13.3",
|
||||
"side-channel-list": "^1.0.0",
|
||||
"object-inspect": "^1.13.4",
|
||||
"side-channel-list": "^1.0.1",
|
||||
"side-channel-map": "^1.0.1",
|
||||
"side-channel-weakmap": "^1.0.2"
|
||||
},
|
||||
@@ -4617,12 +4951,13 @@
|
||||
}
|
||||
},
|
||||
"node_modules/side-channel-list": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.0.tgz",
|
||||
"integrity": "sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==",
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.1.tgz",
|
||||
"integrity": "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"es-errors": "^1.3.0",
|
||||
"object-inspect": "^1.13.3"
|
||||
"object-inspect": "^1.13.4"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
@@ -4635,6 +4970,7 @@
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz",
|
||||
"integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"call-bound": "^1.0.2",
|
||||
"es-errors": "^1.3.0",
|
||||
@@ -4652,6 +4988,7 @@
|
||||
"version": "1.0.2",
|
||||
"resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz",
|
||||
"integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"call-bound": "^1.0.2",
|
||||
"es-errors": "^1.3.0",
|
||||
@@ -5149,6 +5486,12 @@
|
||||
"node": ">=0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/tweetnacl": {
|
||||
"version": "1.0.3",
|
||||
"resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-1.0.3.tgz",
|
||||
"integrity": "sha512-6rt+RN7aOi1nGMyC4Xa5DdYiukl2UWCbcJft7YhxReBGQD7OAM8Pbxw6YMo4r2diNEA8FEmu32YOn9rhaiE5yw==",
|
||||
"license": "Unlicense"
|
||||
},
|
||||
"node_modules/type-detect": {
|
||||
"version": "4.0.8",
|
||||
"resolved": "https://registry.npmjs.org/type-detect/-/type-detect-4.0.8.tgz",
|
||||
@@ -5174,6 +5517,7 @@
|
||||
"version": "1.6.18",
|
||||
"resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz",
|
||||
"integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"media-typer": "0.3.0",
|
||||
"mime-types": "~2.1.24"
|
||||
|
||||
+6
-5
@@ -32,16 +32,17 @@
|
||||
"axios": "^1.9.0",
|
||||
"dotenv": "^16.0.3",
|
||||
"express": "^4.21.3",
|
||||
"pg": "^8.15.5",
|
||||
"node-pg-migrate": "^8.0.4",
|
||||
"pg": "^8.15.5",
|
||||
"qrcode": "^1.5.3",
|
||||
"resend": "^4.0.0",
|
||||
"socket.io": "^4.8.1",
|
||||
"socket.io-client": "^4.8.1",
|
||||
"tweetnacl": "^1.0.3",
|
||||
"uuid": "^9.0.0"
|
||||
,"qrcode": "^1.5.3",
|
||||
"resend": "^4.0.0",
|
||||
"tweetnacl": "^1.0.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"jest": "^29.7.0"
|
||||
"jest": "^29.7.0",
|
||||
"playwright-core": "^1.61.1"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
const Entitlements = require('../multiplayer/entitlements');
|
||||
|
||||
function asInt(value, fallback = 0) {
|
||||
const n = Number(value);
|
||||
return Number.isFinite(n) ? Math.trunc(n) : fallback;
|
||||
}
|
||||
|
||||
function normalizePremiumLevel(value) {
|
||||
if (typeof value !== 'string') return null;
|
||||
const level = value.trim().toLowerCase();
|
||||
if (!level || level === 'free') return null;
|
||||
return level;
|
||||
}
|
||||
|
||||
function normalizePackGrant(input) {
|
||||
if (!input) return null;
|
||||
const grant = typeof input === 'string' ? { id: input } : input;
|
||||
const id = grant.id || grant.packId || grant.pack_id;
|
||||
if (!id || !Entitlements.PACKS[id]) return null;
|
||||
return {
|
||||
id,
|
||||
expiresAt: grant.expiresAt || grant.expires_at || null,
|
||||
source: grant.source || 'product_purchase'
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeProductGrants(product = {}, fallback = {}) {
|
||||
const explicit = product && typeof product.grants === 'object' && product.grants !== null
|
||||
? product.grants
|
||||
: {};
|
||||
const fallbackCredits = asInt(
|
||||
fallback.credits != null
|
||||
? fallback.credits
|
||||
: (asInt(product.credits, 0) + asInt(product.bonus, 0)),
|
||||
0
|
||||
);
|
||||
|
||||
let credits = fallbackCredits;
|
||||
if (explicit.credits != null) {
|
||||
if (typeof explicit.credits === 'object') {
|
||||
credits = asInt(explicit.credits.amount, fallbackCredits);
|
||||
} else {
|
||||
credits = asInt(explicit.credits, fallbackCredits);
|
||||
}
|
||||
}
|
||||
|
||||
const packs = [];
|
||||
const packInputs = Array.isArray(explicit.packs) ? explicit.packs : [];
|
||||
for (const p of packInputs) {
|
||||
const normalized = normalizePackGrant(p);
|
||||
if (normalized && !packs.some(existing => existing.id === normalized.id)) {
|
||||
packs.push(normalized);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
credits: Math.max(0, credits),
|
||||
packs,
|
||||
premiumLevel: normalizePremiumLevel(explicit.premiumLevel || explicit.premium_level)
|
||||
};
|
||||
}
|
||||
|
||||
function serializeProductGrants(grants = {}) {
|
||||
return {
|
||||
credits: asInt(grants.credits, 0),
|
||||
packs: Array.isArray(grants.packs)
|
||||
? grants.packs.map(normalizePackGrant).filter(Boolean)
|
||||
: [],
|
||||
premiumLevel: normalizePremiumLevel(grants.premiumLevel)
|
||||
};
|
||||
}
|
||||
|
||||
function publicGrantSummary(grants = {}) {
|
||||
const normalized = serializeProductGrants(grants);
|
||||
return {
|
||||
credits: normalized.credits,
|
||||
packs: normalized.packs.map(p => p.id),
|
||||
premiumLevel: normalized.premiumLevel
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
normalizeProductGrants,
|
||||
serializeProductGrants,
|
||||
publicGrantSummary
|
||||
};
|
||||
Reference in New Issue
Block a user