@zardoy/flying-squid 0.0.100 → 0.0.102

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.
@@ -7,6 +7,7 @@ export type BreakTimeConfig = {
7
7
  [stateId: number]: number;
8
8
  '*'?: number;
9
9
  };
10
+ rawConfig?: any;
10
11
  };
11
12
  declare global {
12
13
  interface Server {
@@ -32,7 +32,8 @@ function sendBreakTimeConfig(player, serv) {
32
32
  const config = serv.customPlayersBreakTime[player.uuid];
33
33
  const data = {
34
34
  customBreakTime: config?.blocks ?? {},
35
- customBreakTimeToolAllowance: config?.toolNames ?? []
35
+ customBreakTimeToolAllowance: config?.toolNames ?? [],
36
+ ...config?.rawConfig
36
37
  };
37
38
  player._client.writeChannel(CHANNEL_NAME, {
38
39
  newConfiguration: JSON.stringify(data)
@@ -7,7 +7,14 @@ exports.player = exports.server = void 0;
7
7
  const once_1 = __importDefault(require("@tootallnate/once"));
8
8
  const server = function (serv) {
9
9
  serv.quit = async (reason = 'Server closed') => {
10
- serv.cleanupFunctions.forEach(fn => fn());
10
+ serv.cleanupFunctions.forEach(fn => {
11
+ try {
12
+ fn?.();
13
+ }
14
+ catch (err) {
15
+ serv.err('[quit] Error in cleanup function: ' + err);
16
+ }
17
+ });
11
18
  await Promise.all(serv.players.map((player) => {
12
19
  player.kick(reason);
13
20
  return (0, once_1.default)(player, 'disconnected');
@@ -1,6 +1,24 @@
1
1
  import { Vec3 } from 'vec3';
2
+ import { CustomWorld } from './world';
3
+ import { IndexedData } from 'minecraft-data';
2
4
  export declare const server: (serv: Server) => void;
3
5
  export declare const player: (player: Player, serv: Server, { basePositionAntiCheat, positionAntiCheatNotifyPlayer }: Options) => void;
6
+ export declare function isPlayerInsideBlock(player: Player, serv: Server, position: Vec3): boolean;
7
+ export interface SpeedValidationResult {
8
+ isValid: boolean;
9
+ reason: string;
10
+ distanceSquared: number;
11
+ speedLimit: number;
12
+ currentVelocitySquared: number;
13
+ }
14
+ export declare function validateMovementSpeed(player: Player, lastPosition: Vec3, newPosition: Vec3, packetCount: number): SpeedValidationResult;
15
+ export declare function findSafePosition(playerWorld: CustomWorld, mcData: IndexedData, attemptedPosition: Vec3): Vec3 | undefined;
16
+ export declare function isInsideStrict(pos: Vec3, box: AABB): boolean;
17
+ export declare function isInsideExpanded(pos: Vec3, box: AABB, threshold: number): boolean;
18
+ export declare function clampToAABBFromDirection(pos: Vec3, box: AABB): Vec3;
19
+ export declare function clamp(v: number, min: number, max: number): number;
20
+ export declare function distanceToAABB(p: Vec3, box: AABB): number;
21
+ export declare function dist1D(v: number, min: number, max: number): number;
4
22
  export type AABB = {
5
23
  min: Vec3;
6
24
  max: Vec3;
@@ -14,5 +32,6 @@ declare global {
14
32
  safeZones: AABB[];
15
33
  resetSafeZones: () => void;
16
34
  addSafeZones: (x1: number, y1: number, z1: number, x2: number, y2: number, z2: number) => void;
35
+ onSafeZoneViolation?: (player: Player) => Vec3 | void;
17
36
  }
18
37
  }
@@ -1,6 +1,15 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.player = exports.server = void 0;
4
+ exports.isPlayerInsideBlock = isPlayerInsideBlock;
5
+ exports.validateMovementSpeed = validateMovementSpeed;
6
+ exports.findSafePosition = findSafePosition;
7
+ exports.isInsideStrict = isInsideStrict;
8
+ exports.isInsideExpanded = isInsideExpanded;
9
+ exports.clampToAABBFromDirection = clampToAABBFromDirection;
10
+ exports.clamp = clamp;
11
+ exports.distanceToAABB = distanceToAABB;
12
+ exports.dist1D = dist1D;
4
13
  const vec3_1 = require("vec3");
5
14
  // Module to make positions safe to move to.
6
15
  // If a client sends a position outside by more than threshold, ignore and teleport back inside.
@@ -40,10 +49,17 @@ const player = (player, serv, { basePositionAntiCheat = false, positionAntiCheat
40
49
  const currentTime = Date.now();
41
50
  // Check if this is a response to our teleport
42
51
  if (player.pendingTeleport) {
43
- if (position.distanceTo(player.pendingTeleport) < 0.1) {
44
- lastMovementTime = currentTime;
45
- // player.knownPosition = position.clone()
46
- player.pendingTeleport = null;
52
+ cancel(false); // while waiting for teleport confirmation, ignore old movements
53
+ return;
54
+ }
55
+ if (player.validateNextPosition) {
56
+ if (player.validateNextPosition.distanceTo(position) < 0.1) {
57
+ player.validateNextPosition = undefined;
58
+ }
59
+ else {
60
+ player.teleport(player.validateNextPosition);
61
+ cancel(false);
62
+ return;
47
63
  }
48
64
  return;
49
65
  }
@@ -60,7 +76,19 @@ const player = (player, serv, { basePositionAntiCheat = false, positionAntiCheat
60
76
  if (positionAntiCheatNotifyPlayer) {
61
77
  player.chat(`[safeZones] Block collision detected. Teleporting to safe position.`);
62
78
  }
63
- player.teleport(isPlayerInsideBlock(player, serv, lastPosition) ? lastPosition : findSafePosition(player, serv, position));
79
+ let safePosition;
80
+ if (isPlayerInsideBlock(player, serv, lastPosition)) {
81
+ safePosition = lastPosition;
82
+ }
83
+ else {
84
+ safePosition = findSafePosition(player.world, serv.mcData, position);
85
+ if (!safePosition) {
86
+ // dont do anything about it, let player get out themselves
87
+ }
88
+ }
89
+ if (safePosition) {
90
+ player.teleport(safePosition);
91
+ }
64
92
  return;
65
93
  }
66
94
  // Anti-cheat: Movement speed limit (vanilla-like approach)
@@ -123,17 +151,18 @@ const player = (player, serv, { basePositionAntiCheat = false, positionAntiCheat
123
151
  if (isInsideExpanded(position, zone, THRESHOLD))
124
152
  return;
125
153
  // Otherwise, clamp back inside from direction of attempted position
126
- const corrected = clampToAABBFromDirection(position, zone);
154
+ let corrected = clampToAABBFromDirection(position, zone);
155
+ corrected = serv.onSafeZoneViolation?.(player) ?? corrected;
127
156
  // Prevent default cancel handling and perform corrective teleport ourselves
128
157
  if (positionAntiCheatNotifyPlayer) {
129
- player.chat(`[safeZones] Out of bounds. Teleporting to safe position.`);
158
+ player.chat(`[safeZones] Out of bounds ${zone.min.toString()} <-> ${zone.max.toString()}: ${position.toString()} -> ${corrected.toString()}. Teleporting to safe position.`);
130
159
  }
131
160
  cancel(false);
132
161
  player.teleport(corrected);
133
162
  });
134
163
  };
135
164
  exports.player = player;
136
- // Anti-cheat helper functions
165
+ // Anti-cheat helper functions - EXPORTED FOR TESTING
137
166
  function isPlayerInsideBlock(player, serv, position) {
138
167
  const blocks = serv.mcData.blocksByStateId;
139
168
  const chunk = player.world.getLoadedColumnAt(position);
@@ -215,50 +244,55 @@ function validateMovementSpeed(player, lastPosition, newPosition, packetCount) {
215
244
  currentVelocitySquared: estimatedVelocitySquared
216
245
  };
217
246
  }
218
- function findSafePosition(player, serv, attemptedPosition) {
247
+ function findSafePosition(playerWorld, mcData, attemptedPosition) {
219
248
  // Start from the attempted position and search nearby for a safe spot
220
249
  const basePosition = attemptedPosition.floored();
221
250
  const getBlock = (pos) => {
222
- const chunk = player.world.getLoadedColumnAt(pos);
251
+ const chunk = playerWorld.getLoadedColumnAt(pos);
223
252
  if (!chunk)
224
253
  return null;
225
254
  return chunk.getBlockStateId(new vec3_1.Vec3(Math.floor(pos.x) & 15, Math.floor(pos.y), Math.floor(pos.z) & 15));
226
255
  };
227
- // Search in expanding radius for a safe position
228
- for (let radius = 0; radius <= 3; radius++) {
256
+ const SEARCH_RADIUS = 5;
257
+ // Search in expanding radius in all directions except downward (x, z, y+)
258
+ // Start with radius 0 (current position), then expand outward
259
+ for (let radius = 0; radius <= SEARCH_RADIUS; radius++) {
260
+ // Search in a cube pattern but only allow y >= 0 (no downward search)
229
261
  for (let x = -radius; x <= radius; x++) {
230
262
  for (let z = -radius; z <= radius; z++) {
231
- if (Math.abs(x) === radius || Math.abs(z) === radius) { // Only check edge positions for efficiency
232
- const testPos = basePosition.offset(x, 0, z);
233
- // Check if position is safe (not inside blocks)
234
- let isSafe = true;
235
- for (let y = 0; y < Math.ceil(PLAYER_SIZE.y); y++) {
236
- const checkPos = testPos.offset(0, y, 0);
237
- try {
238
- const blockStateId = getBlock(checkPos);
239
- if (blockStateId === null || serv.mcData.blocksByStateId[blockStateId]?.boundingBox === 'block') {
263
+ for (let y = 0; y <= radius; y++) { // Only search upward and at same level, never down
264
+ // Only check positions at the current radius for efficiency
265
+ if (Math.abs(x) === radius || Math.abs(z) === radius || y === radius) {
266
+ const testPos = basePosition.offset(x, y, z);
267
+ // Check if position is safe (not inside blocks)
268
+ let isSafe = true;
269
+ for (let checkY = 0; checkY < Math.ceil(PLAYER_SIZE.y); checkY++) {
270
+ const checkPos = testPos.offset(0, checkY, 0);
271
+ try {
272
+ const blockStateId = getBlock(checkPos);
273
+ if (blockStateId === null || mcData.blocksByStateId[blockStateId]?.boundingBox === 'block') {
274
+ isSafe = false;
275
+ break;
276
+ }
277
+ }
278
+ catch {
279
+ // If we can't check, assume unsafe
240
280
  isSafe = false;
241
281
  break;
242
282
  }
243
283
  }
244
- catch {
245
- // If we can't check, assume unsafe
246
- isSafe = false;
247
- break;
284
+ if (isSafe) {
285
+ return testPos.offset(0.5, 0, 0.5); // Center in block
248
286
  }
249
287
  }
250
- if (isSafe) {
251
- return testPos.offset(0.5, 0, 0.5); // Center in block
252
- }
253
288
  }
254
289
  }
255
290
  }
256
291
  }
257
- serv.warn('[safeZones] no safe position found');
258
- // If no safe position found, return player's current position
259
- return player.position;
292
+ // Return undefined if no safe position found
293
+ return undefined;
260
294
  }
261
- // Original helper functions
295
+ // Helper functions - EXPORTED FOR TESTING
262
296
  function isInsideStrict(pos, box) {
263
297
  return pos.x >= box.min.x && pos.x <= box.max.x &&
264
298
  pos.y >= box.min.y && pos.y <= box.max.y &&
@@ -3,9 +3,14 @@ export declare const player: (player: Player) => void;
3
3
  export declare const entity: (entity: Entity, serv: Server) => void;
4
4
  declare global {
5
5
  interface Player {
6
+ lastTeleportId: number;
7
+ validateNextPosition?: Vec3;
6
8
  "sendAbilities": () => void;
7
9
  /** Position we're expecting the client to move to after teleport */
8
- pendingTeleport?: Vec3 | null;
10
+ pendingTeleport?: {
11
+ position: Vec3;
12
+ teleportId: number;
13
+ };
9
14
  }
10
15
  interface Entity {
11
16
  /** ID of entity on server */
@@ -14,6 +19,7 @@ declare global {
14
19
  position: Vec3;
15
20
  /** Used to calculate collisions for server-side entities */
16
21
  size: Vec3;
22
+ knownPosition: Vec3;
17
23
  /** Yaw of entity (rotation looking up and down) */
18
24
  yaw: number;
19
25
  /** Pitch of entity (rotation sideways) */
@@ -56,6 +56,7 @@ const player = function (player) {
56
56
  player.sendPosition((new vec3_1.Vec3(x, y, z)), onGround);
57
57
  receivedLook(yaw, pitch, onGround);
58
58
  });
59
+ player.lastTeleportId ??= 0;
59
60
  player.sendSelfPosition = (sendChunks = true) => {
60
61
  // double position in all versions
61
62
  player._client.write('position', {
@@ -65,28 +66,31 @@ const player = function (player) {
65
66
  yaw: convToClient(player.yaw),
66
67
  pitch: convToClient(player.pitch),
67
68
  flags: 0x00,
68
- teleportId: 1
69
+ teleportId: ++player.lastTeleportId
69
70
  });
70
71
  if (sendChunks)
71
72
  player.sendChunkWhenMove();
72
73
  };
73
- let oldSetTimeout;
74
74
  player.teleport = async (position) => {
75
- // Track pending teleport for anti-cheat
76
- if (oldSetTimeout)
77
- clearTimeout(oldSetTimeout);
78
- player.pendingTeleport = position.clone();
79
75
  const notCancelled = await player.sendPosition(position, false, true);
80
76
  if (!notCancelled)
81
77
  return;
82
78
  player.sendSelfPosition();
83
- // Clear pending teleport after a short delay to handle network latency
84
- oldSetTimeout = player.setTimeout(() => {
85
- if (player.pendingTeleport?.equals(position)) {
86
- player.pendingTeleport = null;
87
- }
88
- }, 1000); // 1 second timeout
79
+ player.pendingTeleport = {
80
+ position: position.clone(),
81
+ teleportId: player.lastTeleportId
82
+ };
89
83
  };
84
+ player.onPacket('teleport_confirm', ({ teleportId }) => {
85
+ if (teleportId === player.lastTeleportId && player.pendingTeleport) {
86
+ // validate the position
87
+ player.validateNextPosition = player.pendingTeleport.position;
88
+ player.pendingTeleport = undefined;
89
+ }
90
+ else {
91
+ console.log('Invalid teleport confirm packet received', player.pendingTeleport, 'received:', teleportId);
92
+ }
93
+ });
90
94
  player.sendAbilities = () => {
91
95
  const isInvulnerable = player.gameMode === 1 || player.gameMode === 3; // Creative or Spectator
92
96
  const canFly = player.gameMode === 1 || player.gameMode === 3;
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.100",
4
+ "version": "0.0.102",
5
5
  "main": "dist/index.js",
6
6
  "types": "./dist/index.d.ts",
7
7
  "bin": "dist/app.js",
@@ -38,6 +38,7 @@
38
38
  "prismarine-chunk": "^1.39.0",
39
39
  "prismarine-entity": "^2.5.0",
40
40
  "prismarine-item": "^1.17.0",
41
+ "prismarine-block": "^1.22.0",
41
42
  "prismarine-nbt": "^2.7.0",
42
43
  "prismarine-provider-anvil": "github:zardoy/prismarine-provider-anvil#everything",
43
44
  "prismarine-windows": "^2.8.0",