@zardoy/flying-squid 0.0.82 → 0.0.83

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,18 @@
1
+ export declare const server: (serv: Server, options: Options) => {
2
+ lastSyncRequests: Map<string, {
3
+ time: number;
4
+ requestId: number;
5
+ }>;
6
+ nextRequestId: number;
7
+ /** @internal */
8
+ requestSync: (player: Player) => void;
9
+ handleSyncResponse: (player: Player, data: {
10
+ data: string;
11
+ }) => void;
12
+ };
13
+ export declare const player: (player: Player, serv: Server) => void;
14
+ declare global {
15
+ interface Server {
16
+ customSync: ReturnType<typeof server>;
17
+ }
18
+ }
@@ -0,0 +1,122 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.player = exports.server = void 0;
4
+ const SYNC_REQUEST_CHANNEL = 'minecraft-web-client:sync-request';
5
+ const SYNC_RESPONSE_CHANNEL = 'minecraft-web-client:sync-response';
6
+ const CHECK_INTERVAL = 1000; // 1 second
7
+ const server = (serv, options) => {
8
+ const module = {
9
+ // Track when we last requested sync from each player
10
+ lastSyncRequests: new Map(),
11
+ nextRequestId: 0,
12
+ // Request entity list from a player
13
+ /** @internal */
14
+ requestSync: (player) => {
15
+ const requestId = module.nextRequestId++;
16
+ const request = {
17
+ requestId,
18
+ time: Date.now()
19
+ };
20
+ player._client.writeChannel(SYNC_REQUEST_CHANNEL, {
21
+ data: JSON.stringify({ requestId })
22
+ });
23
+ module.lastSyncRequests.set(player.uuid, request);
24
+ },
25
+ // Handle sync response from client
26
+ handleSyncResponse: (player, data) => {
27
+ try {
28
+ const parsed = JSON.parse(data.data);
29
+ // Type guard to validate response shape
30
+ const isValidResponse = (obj) => {
31
+ return typeof obj === 'object' && obj !== null &&
32
+ typeof obj.requestId === 'number' &&
33
+ Array.isArray(obj.entityIds) &&
34
+ obj.entityIds.every(id => typeof id === 'number');
35
+ };
36
+ if (!isValidResponse(parsed)) {
37
+ throw new Error('Invalid response format');
38
+ }
39
+ const { requestId, entityIds } = parsed;
40
+ // Verify this is a response to our last request
41
+ const lastRequest = module.lastSyncRequests.get(player.uuid);
42
+ if (!lastRequest || lastRequest.requestId !== requestId) {
43
+ return; // Ignore out of order responses
44
+ }
45
+ // Calculate and update latency
46
+ const latency = Date.now() - lastRequest.time;
47
+ player._client.latency = latency;
48
+ // Clean up the request
49
+ module.lastSyncRequests.delete(player.uuid);
50
+ const trackedIds = new Set(entityIds);
51
+ const expectedIds = new Set();
52
+ // Find entities that should be visible to the player
53
+ for (const entity of Object.values(serv.entities)) {
54
+ if (entity.id === player.id)
55
+ continue; // Skip self
56
+ // Check if entity is within view distance
57
+ const dx = entity.position.x - player.position.x;
58
+ const dy = entity.position.y - player.position.y;
59
+ const dz = entity.position.z - player.position.z;
60
+ const distanceSquared = dx * dx + dy * dy + dz * dz;
61
+ const viewDistance = entity.viewDistance ?? 150;
62
+ if (distanceSquared <= viewDistance * viewDistance) {
63
+ expectedIds.add(entity.id);
64
+ }
65
+ }
66
+ // Find missing entities
67
+ for (const entityId of expectedIds) {
68
+ if (!trackedIds.has(entityId)) {
69
+ const entity = serv.entities[entityId];
70
+ if (!entity)
71
+ continue;
72
+ serv.warn(`Player ${player.username} missing entity ${entityId} (${entity.name ?? entity.type}), respawning... (ping: ${latency}ms)`);
73
+ // Respawn the entity for this player
74
+ player._client.write(entity.spawnPacketName, entity.getSpawnPacket());
75
+ // Send metadata if needed
76
+ if (serv.supportFeature('entityMetadataSentSeparately')) {
77
+ entity.sendMetadata(entity.metadata);
78
+ }
79
+ }
80
+ }
81
+ // Log extra entities (debugging)
82
+ for (const entityId of trackedIds) {
83
+ if (!expectedIds.has(entityId) && !serv.entities[entityId]) {
84
+ serv.warn(`Player ${player.username} tracking non-existent entity ${entityId}`);
85
+ }
86
+ }
87
+ }
88
+ catch (err) {
89
+ serv.err(`Error handling sync response from ${player.username}: ${err}`);
90
+ }
91
+ }
92
+ };
93
+ serv.customSync = module;
94
+ return module;
95
+ };
96
+ exports.server = server;
97
+ const player = (player, serv) => {
98
+ // Register sync channels with simplified string format
99
+ player._client.registerChannel(SYNC_REQUEST_CHANNEL, ['container', [
100
+ {
101
+ name: 'data',
102
+ type: ['pstring', { countType: 'i16' }]
103
+ }
104
+ ]]);
105
+ player._client.registerChannel(SYNC_RESPONSE_CHANNEL, ['container', [
106
+ {
107
+ name: 'data',
108
+ type: ['pstring', { countType: 'i16' }]
109
+ }
110
+ ]]);
111
+ // Handle sync responses from client
112
+ player._client.on(SYNC_RESPONSE_CHANNEL, (data) => {
113
+ serv.customSync.handleSyncResponse(player, data);
114
+ });
115
+ // Start periodic sync checks
116
+ player.on('spawned', () => {
117
+ player.setInterval(() => {
118
+ serv.customSync.requestSync(player);
119
+ }, CHECK_INTERVAL);
120
+ });
121
+ };
122
+ exports.player = player;
@@ -1,7 +1,7 @@
1
1
  export declare const server: (serv: Server) => {
2
- customWaypoints: Record<string, Waypoint>;
3
- customAddWaypoint: (id: string, waypoint: Waypoint) => void;
4
- customRemoveWaypoint: (id: string) => void;
2
+ waypoints: Record<string, Waypoint>;
3
+ addWaypoint: (id: string, waypoint: Waypoint, players?: Player[]) => void;
4
+ removeWaypoint: (id: string) => void;
5
5
  };
6
6
  export declare const player: (player: Player, serv: Server) => Promise<void>;
7
7
  export type Waypoint = {
@@ -11,6 +11,7 @@ export type Waypoint = {
11
11
  minDistance?: number;
12
12
  label?: string;
13
13
  color?: number;
14
+ _players?: string[];
14
15
  };
15
16
  declare global {
16
17
  interface Server {
@@ -5,16 +5,16 @@ const ADD_CHANNEL = 'minecraft-web-client:waypoint-add';
5
5
  const DELETE_CHANNEL = 'minecraft-web-client:waypoint-delete';
6
6
  const server = (serv) => {
7
7
  const module = {
8
- customWaypoints: {},
9
- customAddWaypoint: (id, waypoint) => {
10
- serv.customWaypoints.customWaypoints[id] = waypoint;
8
+ waypoints: {},
9
+ addWaypoint: (id, waypoint, players) => {
10
+ module.waypoints[id] = { ...waypoint, _players: players ? players.map(p => p.uuid) : undefined };
11
11
  // Broadcast add/update to all online players
12
- for (const player of serv.players ?? []) {
12
+ for (const player of (players ?? serv.players ?? [])) {
13
13
  sendAddWaypoint(player, id, waypoint);
14
14
  }
15
15
  },
16
- customRemoveWaypoint: (id) => {
17
- delete serv.customWaypoints.customWaypoints[id];
16
+ removeWaypoint: (id) => {
17
+ delete module.waypoints[id];
18
18
  // Broadcast delete to all online players
19
19
  for (const player of serv.players ?? []) {
20
20
  sendDeleteWaypoint(player, id);
@@ -40,9 +40,11 @@ function sendDeleteWaypoint(player, id) {
40
40
  player._client.writeChannel(DELETE_CHANNEL, { id });
41
41
  }
42
42
  function sendAllWaypoints(player, serv) {
43
- const entries = Object.entries(serv.customWaypoints.customWaypoints ?? {});
43
+ const entries = Object.entries(serv.customWaypoints.waypoints ?? {});
44
44
  for (const [id, waypoint] of entries) {
45
- sendAddWaypoint(player, id, waypoint);
45
+ if (!waypoint._players || waypoint._players.includes(player.uuid)) {
46
+ sendAddWaypoint(player, id, waypoint);
47
+ }
46
48
  }
47
49
  }
48
50
  const player = async (player, serv) => {
@@ -32,4 +32,6 @@ declare global {
32
32
  isFresh: boolean;
33
33
  _sessionStartMs: number;
34
34
  }
35
+ interface ServerDatabase {
36
+ }
35
37
  }
@@ -142,6 +142,7 @@ const player = function (player, serv, { version }) {
142
142
  });
143
143
  }
144
144
  }
145
+ const blockDropVelocity = new vec3_1.Vec3(Math.random() * 4 - 2, Math.random() * 2 + 2, Math.random() * 4 - 2);
145
146
  async function completeDigging(location) {
146
147
  clearInterval(animationInterval);
147
148
  const diggingTime = Date.now() - startDiggingTime;
@@ -168,18 +169,24 @@ const player = function (player, serv, { version }) {
168
169
  if (typeof mcData.blockLoot === 'undefined') {
169
170
  drops.push({
170
171
  ...dropBase,
171
- blockDropVelocity: new vec3_1.Vec3(Math.random() * 4 - 2, Math.random() * 2 + 2, Math.random() * 4 - 2),
172
+ blockDropVelocity: blockDropVelocity,
172
173
  blockDropId: serv.supportFeature('theFlattening') ? currentlyDugBlock.drops?.[0] : currentlyDugBlock.type
173
174
  });
174
175
  }
175
176
  else {
176
177
  const heldItem = player.inventory.slots[36 + player.heldItemSlot];
177
- const silkTouch = heldItem?.enchants.map(enchant => enchant.name).includes('silk_touch');
178
+ let enchants;
179
+ try {
180
+ enchants = heldItem?.enchants;
181
+ }
182
+ catch (e) {
183
+ }
184
+ const silkTouch = enchants?.map(enchant => enchant.name).includes('silk_touch');
178
185
  const blockDrops = mcData.blockLoot[currentlyDugBlock.name].drops.filter(drop => !(drop[`${silkTouch ? 'noS' : 's'}ilkTouch`] ?? false));
179
186
  for (const drop of blockDrops) {
180
187
  drops.push({
181
188
  ...dropBase,
182
- blockDropVelocity: new vec3_1.Vec3(Math.random() * 4 - 2, Math.random() * 2 + 2, Math.random() * 4 - 2),
189
+ blockDropVelocity: blockDropVelocity,
183
190
  blockDropId: mcData.itemsByName[drop.item].id
184
191
  });
185
192
  }
@@ -240,7 +247,7 @@ const player = function (player, serv, { version }) {
240
247
  dropBlock: false,
241
248
  blockDropPosition: location.offset(0.5, 0.5, 0.5),
242
249
  blockDropWorld: player.world,
243
- blockDropVelocity: new vec3_1.Vec3(Math.random() * 4 - 2, Math.random() * 2 + 2, Math.random() * 4 - 2),
250
+ blockDropVelocity: blockDropVelocity,
244
251
  blockDropId: currentlyDugBlock.type,
245
252
  blockDropDamage: currentlyDugBlock.metadata,
246
253
  blockDropPickup: 500,
@@ -15,6 +15,7 @@ module.exports = {
15
15
  'communication': require('./communication'),
16
16
  'crafting': require('./crafting'),
17
17
  'customBlockBreakTime': require('./customBlockBreakTime'),
18
+ 'customSync': require('./customSync'),
18
19
  'customWaypoints': require('./customWaypoints'),
19
20
  'database': require('./database'),
20
21
  'daycycle': require('./daycycle'),
@@ -3,6 +3,8 @@ export declare const entity: (entity: Entity, serv: Server) => void;
3
3
  export declare const server: (serv: Server) => void;
4
4
  declare global {
5
5
  interface Entity {
6
+ /** Whether the entity is invincible to all damage */
7
+ invincible: boolean;
6
8
  /** How many half-hearts an entity has of health (e.g. Player has 20). Not really used for objects, only players and mobs. */
7
9
  health: number;
8
10
  /** * sound: Sound to play (default is game.player.hurt)
@@ -7,15 +7,35 @@ exports.server = exports.entity = exports.player = void 0;
7
7
  const vec3_1 = require("vec3");
8
8
  const chalk_1 = __importDefault(require("chalk"));
9
9
  const user_error_1 = __importDefault(require("../user_error"));
10
+ const MAX_ATTACK_DISTANCE = 4; // Maximum reach in blocks
11
+ const ATTACK_COOLDOWN_MS = 250; // Minimum time between attacks
12
+ const DEFAULT_KNOCKBACK = new vec3_1.Vec3(0, 0.4, 0); // Base vertical knockback
13
+ const KNOCKBACK_MULTIPLIER = 0.4; // Horizontal knockback scaling
10
14
  const player = function (player, serv) {
15
+ let lastAttackTime = 0;
11
16
  function attackEntity(entityId) {
12
17
  const attackedEntity = serv.entities[entityId];
13
18
  const attackedPlayer = attackedEntity.type === 'player' ? attackedEntity : undefined;
14
- if (!attackedEntity || (attackedPlayer && attackedPlayer.gameMode !== 0))
19
+ if (!attackedEntity)
15
20
  return;
21
+ if (attackedPlayer && (attackedPlayer.gameMode === 1 || attackedPlayer.gameMode === 3 || attackedPlayer.invincible))
22
+ return;
23
+ // Anti-cheat: Distance check
24
+ const distance = player.position.distanceTo(attackedEntity.position);
25
+ if (distance > MAX_ATTACK_DISTANCE) {
26
+ return; // Silently fail suspicious attacks
27
+ }
28
+ // Rate limiting
29
+ const now = Date.now();
30
+ if (now - lastAttackTime < ATTACK_COOLDOWN_MS)
31
+ return;
32
+ lastAttackTime = now;
33
+ // Calculate knockback direction and strength
34
+ const knockbackDir = attackedEntity.position.minus(player.position).normalize();
35
+ const velocity = DEFAULT_KNOCKBACK.plus(knockbackDir.scaled(KNOCKBACK_MULTIPLIER));
16
36
  player.behavior('attack', {
17
37
  attackedEntity,
18
- velocity: attackedEntity.position.minus(player.position).plus(new vec3_1.Vec3(0, 0.5, 0)).scaled(5)
38
+ velocity
19
39
  }, (o) => o.attackedEntity.takeDamage(o));
20
40
  }
21
41
  player._client.on('use_entity', ({ mouse, target } = {}) => {
@@ -35,7 +55,10 @@ const player = function (player, serv) {
35
55
  };
36
56
  exports.player = player;
37
57
  const entity = function (entity, serv) {
58
+ entity.invincible = false;
38
59
  entity.takeDamage = ({ sound = 'game.player.hurt', damage = 1, velocity = new vec3_1.Vec3(0, 0, 0), maxVelocity = new vec3_1.Vec3(4, 4, 4), animation = true }) => {
60
+ if (entity.invincible)
61
+ return;
39
62
  entity.updateHealth(entity.health - damage);
40
63
  serv.playSound(sound, entity.world, entity.position);
41
64
  entity.sendVelocity(velocity, maxVelocity);
@@ -73,6 +96,7 @@ const server = function (serv) {
73
96
  info: 'Kill entities',
74
97
  usage: '/kill <selector>|<player>',
75
98
  tab: ['player'],
99
+ op: true,
76
100
  parse(str) {
77
101
  return str || false;
78
102
  },
@@ -105,6 +129,7 @@ const server = function (serv) {
105
129
  info: 'Applies damage to the specified entities',
106
130
  usage: '/damage',
107
131
  tab: ['player', 'number'],
132
+ op: true,
108
133
  parse(string, ctx) {
109
134
  return string.split(' '); // todo validate
110
135
  },
@@ -28,6 +28,7 @@ declare global {
28
28
  /** Alias to serv.overworld.seed */
29
29
  seed: number;
30
30
  writeLevelDat: () => Promise<void>;
31
+ broadcastSaved?: boolean;
31
32
  "overworldOriginalGenerator": (chunkX: number, chunkZ: number) => any;
32
33
  "overworldGeneratorOverride"?: (chunkX: number, chunkZ: number, generationOptions: any) => any;
33
34
  }
@@ -344,7 +344,7 @@ const server = async function (serv, options) {
344
344
  console.log('worlds init done');
345
345
  // Periodic autosave: world and all players
346
346
  const autosaveMs = options.savingInterval === false ? 0 : (typeof options.savingInterval === 'number' ? options.savingInterval : 60_000);
347
- if (autosaveMs > 0) {
347
+ if (autosaveMs > 0 && options.worldFolder) {
348
348
  let lastBroadcastTs = 0;
349
349
  const doAutosave = async () => {
350
350
  try {
@@ -358,7 +358,7 @@ const server = async function (serv, options) {
358
358
  await serv.saveAllPlayerDataToDisk?.();
359
359
  // Broadcast a single "Server saved" message (no spam more than once per interval)
360
360
  const now = Date.now();
361
- if (now - lastBroadcastTs > autosaveMs - 100) {
361
+ if (now - lastBroadcastTs > autosaveMs - 10_000 && serv.broadcastSaved !== false) {
362
362
  serv.broadcast('§7[autosave] Server saved');
363
363
  lastBroadcastTs = now;
364
364
  }
package/dist/types.d.ts CHANGED
@@ -12,6 +12,7 @@ import "./lib/modules/commands.d.ts"
12
12
  import "./lib/modules/communication.d.ts"
13
13
  import "./lib/modules/crafting.d.ts"
14
14
  import "./lib/modules/customBlockBreakTime.d.ts"
15
+ import "./lib/modules/customSync.d.ts"
15
16
  import "./lib/modules/customWaypoints.d.ts"
16
17
  import "./lib/modules/database.d.ts"
17
18
  import "./lib/modules/daycycle.d.ts"
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@zardoy/flying-squid",
3
3
  "description": "A minecraft server written in TS",
4
- "version": "0.0.82",
4
+ "version": "0.0.83",
5
5
  "main": "dist/index.js",
6
6
  "types": "./dist/index.d.ts",
7
7
  "bin": "dist/app.js",