@zardoy/flying-squid 0.0.101 → 0.0.103

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.
@@ -15,4 +15,8 @@ declare global {
15
15
  /** Get current log file path */
16
16
  "getLogPath": () => string | null;
17
17
  }
18
+ interface Options {
19
+ /** Whether to redirect console.log output to server log file. Defaults to true. */
20
+ noConsoleLogRedirect?: boolean;
21
+ }
18
22
  }
@@ -185,16 +185,22 @@ const server = function (serv, settings) {
185
185
  const orig = console.log;
186
186
  return function () {
187
187
  readline.cursorTo(process.stdout, 0);
188
- // let tmp
189
- // try {
190
- // tmp = process.stdout
191
- // // @ts-ignore
192
- // process.stdout = process.stderr
193
- // orig.apply(console, arguments)
194
- // } finally {
195
- // process.stdout = tmp
196
- // }
188
+ // Apply original console.log to stdout
197
189
  orig.apply(console, arguments);
190
+ // Redirect to server log if enabled and not disabled
191
+ if (!settings.noConsoleLogRedirect && logStream?.writable) {
192
+ const args = Array.from(arguments);
193
+ const message = args.map(arg => typeof arg === 'object' ? JSON.stringify(arg, null, 2) : String(arg)).join(' ');
194
+ // Add timestamp and prefix for console.log entries
195
+ const timestamp = new Date().toISOString();
196
+ const logEntry = `[${timestamp}] [CONSOLE]: ${message}\n`;
197
+ try {
198
+ logStream.write(logEntry);
199
+ }
200
+ catch (err) {
201
+ // Silently fail if log writing fails to avoid infinite loops
202
+ }
203
+ }
198
204
  rl.prompt(true);
199
205
  };
200
206
  })();
@@ -1,7 +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;
4
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;
5
22
  export type AABB = {
6
23
  min: Vec3;
7
24
  max: Vec3;
@@ -1,7 +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;
4
7
  exports.isInsideStrict = isInsideStrict;
8
+ exports.isInsideExpanded = isInsideExpanded;
9
+ exports.clampToAABBFromDirection = clampToAABBFromDirection;
10
+ exports.clamp = clamp;
11
+ exports.distanceToAABB = distanceToAABB;
12
+ exports.dist1D = dist1D;
5
13
  const vec3_1 = require("vec3");
6
14
  // Module to make positions safe to move to.
7
15
  // If a client sends a position outside by more than threshold, ignore and teleport back inside.
@@ -41,10 +49,17 @@ const player = (player, serv, { basePositionAntiCheat = false, positionAntiCheat
41
49
  const currentTime = Date.now();
42
50
  // Check if this is a response to our teleport
43
51
  if (player.pendingTeleport) {
44
- if (position.distanceTo(player.pendingTeleport) < 0.1) {
45
- lastMovementTime = currentTime;
46
- // player.knownPosition = position.clone()
47
- 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;
48
63
  }
49
64
  return;
50
65
  }
@@ -61,7 +76,19 @@ const player = (player, serv, { basePositionAntiCheat = false, positionAntiCheat
61
76
  if (positionAntiCheatNotifyPlayer) {
62
77
  player.chat(`[safeZones] Block collision detected. Teleporting to safe position.`);
63
78
  }
64
- 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
+ }
65
92
  return;
66
93
  }
67
94
  // Anti-cheat: Movement speed limit (vanilla-like approach)
@@ -121,11 +148,16 @@ const player = (player, serv, { basePositionAntiCheat = false, positionAntiCheat
121
148
  return;
122
149
  }
123
150
  // If new position is within expanded bounds (threshold), allow it
124
- if (isInsideExpanded(position, zone, THRESHOLD))
151
+ if (isInsideExpanded(position, zone))
125
152
  return;
126
153
  // Otherwise, clamp back inside from direction of attempted position
127
154
  let corrected = clampToAABBFromDirection(position, zone);
128
- corrected = serv.onSafeZoneViolation?.(player) ?? corrected;
155
+ let customCorrection = serv.onSafeZoneViolation?.(player);
156
+ if (customCorrection && !isInsideExpanded(customCorrection, zone)) {
157
+ serv.emit('error', new Error('Invalid custom zone pos correction!'));
158
+ customCorrection = undefined;
159
+ }
160
+ corrected = customCorrection ?? corrected;
129
161
  // Prevent default cancel handling and perform corrective teleport ourselves
130
162
  if (positionAntiCheatNotifyPlayer) {
131
163
  player.chat(`[safeZones] Out of bounds ${zone.min.toString()} <-> ${zone.max.toString()}: ${position.toString()} -> ${corrected.toString()}. Teleporting to safe position.`);
@@ -135,7 +167,7 @@ const player = (player, serv, { basePositionAntiCheat = false, positionAntiCheat
135
167
  });
136
168
  };
137
169
  exports.player = player;
138
- // Anti-cheat helper functions
170
+ // Anti-cheat helper functions - EXPORTED FOR TESTING
139
171
  function isPlayerInsideBlock(player, serv, position) {
140
172
  const blocks = serv.mcData.blocksByStateId;
141
173
  const chunk = player.world.getLoadedColumnAt(position);
@@ -217,56 +249,61 @@ function validateMovementSpeed(player, lastPosition, newPosition, packetCount) {
217
249
  currentVelocitySquared: estimatedVelocitySquared
218
250
  };
219
251
  }
220
- function findSafePosition(player, serv, attemptedPosition) {
252
+ function findSafePosition(playerWorld, mcData, attemptedPosition) {
221
253
  // Start from the attempted position and search nearby for a safe spot
222
254
  const basePosition = attemptedPosition.floored();
223
255
  const getBlock = (pos) => {
224
- const chunk = player.world.getLoadedColumnAt(pos);
256
+ const chunk = playerWorld.getLoadedColumnAt(pos);
225
257
  if (!chunk)
226
258
  return null;
227
259
  return chunk.getBlockStateId(new vec3_1.Vec3(Math.floor(pos.x) & 15, Math.floor(pos.y), Math.floor(pos.z) & 15));
228
260
  };
229
- // Search in expanding radius for a safe position
230
- for (let radius = 0; radius <= 3; radius++) {
261
+ const SEARCH_RADIUS = 5;
262
+ // Search in expanding radius in all directions except downward (x, z, y+)
263
+ // Start with radius 0 (current position), then expand outward
264
+ for (let radius = 0; radius <= SEARCH_RADIUS; radius++) {
265
+ // Search in a cube pattern but only allow y >= 0 (no downward search)
231
266
  for (let x = -radius; x <= radius; x++) {
232
267
  for (let z = -radius; z <= radius; z++) {
233
- if (Math.abs(x) === radius || Math.abs(z) === radius) { // Only check edge positions for efficiency
234
- const testPos = basePosition.offset(x, 0, z);
235
- // Check if position is safe (not inside blocks)
236
- let isSafe = true;
237
- for (let y = 0; y < Math.ceil(PLAYER_SIZE.y); y++) {
238
- const checkPos = testPos.offset(0, y, 0);
239
- try {
240
- const blockStateId = getBlock(checkPos);
241
- if (blockStateId === null || serv.mcData.blocksByStateId[blockStateId]?.boundingBox === 'block') {
268
+ for (let y = 0; y <= radius; y++) { // Only search upward and at same level, never down
269
+ // Only check positions at the current radius for efficiency
270
+ if (Math.abs(x) === radius || Math.abs(z) === radius || y === radius) {
271
+ const testPos = basePosition.offset(x, y, z);
272
+ // Check if position is safe (not inside blocks)
273
+ let isSafe = true;
274
+ for (let checkY = 0; checkY < Math.ceil(PLAYER_SIZE.y); checkY++) {
275
+ const checkPos = testPos.offset(0, checkY, 0);
276
+ try {
277
+ const blockStateId = getBlock(checkPos);
278
+ if (blockStateId === null || mcData.blocksByStateId[blockStateId]?.boundingBox === 'block') {
279
+ isSafe = false;
280
+ break;
281
+ }
282
+ }
283
+ catch {
284
+ // If we can't check, assume unsafe
242
285
  isSafe = false;
243
286
  break;
244
287
  }
245
288
  }
246
- catch {
247
- // If we can't check, assume unsafe
248
- isSafe = false;
249
- break;
289
+ if (isSafe) {
290
+ return testPos.offset(0.5, 0, 0.5); // Center in block
250
291
  }
251
292
  }
252
- if (isSafe) {
253
- return testPos.offset(0.5, 0, 0.5); // Center in block
254
- }
255
293
  }
256
294
  }
257
295
  }
258
296
  }
259
- serv.warn('[safeZones] no safe position found');
260
- // If no safe position found, return player's current position
261
- return player.position;
297
+ // Return undefined if no safe position found
298
+ return undefined;
262
299
  }
263
- // Original helper functions
300
+ // Helper functions - EXPORTED FOR TESTING
264
301
  function isInsideStrict(pos, box) {
265
302
  return pos.x >= box.min.x && pos.x <= box.max.x &&
266
303
  pos.y >= box.min.y && pos.y <= box.max.y &&
267
304
  pos.z >= box.min.z && pos.z <= box.max.z;
268
305
  }
269
- function isInsideExpanded(pos, box, threshold) {
306
+ function isInsideExpanded(pos, box, threshold = THRESHOLD) {
270
307
  return pos.x >= (box.min.x - threshold) && pos.x <= (box.max.x + threshold) &&
271
308
  pos.y >= (box.min.y - threshold) && pos.y <= (box.max.y + threshold) &&
272
309
  pos.z >= (box.min.z - threshold) && pos.z <= (box.max.z + threshold);
@@ -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 */
@@ -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,33 @@ 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 (!player.lastTeleportId)
86
+ return;
87
+ if (teleportId === player.lastTeleportId && player.pendingTeleport) {
88
+ // validate the position
89
+ player.validateNextPosition = player.pendingTeleport.position;
90
+ player.pendingTeleport = undefined;
91
+ }
92
+ else {
93
+ // console.log('Invalid teleport confirm packet received', player.pendingTeleport, 'received:', teleportId)
94
+ }
95
+ });
90
96
  player.sendAbilities = () => {
91
97
  const isInvulnerable = player.gameMode === 1 || player.gameMode === 3; // Creative or Spectator
92
98
  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.101",
4
+ "version": "0.0.103",
5
5
  "main": "dist/index.js",
6
6
  "types": "./dist/index.d.ts",
7
7
  "bin": "dist/app.js",