@zardoy/flying-squid 0.0.88 → 0.0.90

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.
@@ -2,5 +2,24 @@ export declare const entity: (entity: Entity, serv: Server) => void;
2
2
  export declare const server: (serv: Server, options: Options) => void;
3
3
  declare global {
4
4
  interface Entity {
5
+ "effects": Record<string, {
6
+ amplifier: number;
7
+ duration: number;
8
+ particles: boolean;
9
+ end: number;
10
+ timeout: NodeJS.Timeout;
11
+ } | null>;
12
+ "addEffect": (effectId: number, opt?: {
13
+ amplifier?: number;
14
+ duration?: number;
15
+ particles?: boolean;
16
+ whitelist?: Entity[];
17
+ blacklist?: Entity[];
18
+ override?: boolean;
19
+ }) => boolean;
20
+ removeEffect: (effectId: number, opt?: {
21
+ whitelist?: Entity[];
22
+ blacklist?: Entity[];
23
+ }) => void;
5
24
  }
6
25
  }
@@ -53,6 +53,8 @@ const entity = function (entity, serv) {
53
53
  return false;
54
54
  };
55
55
  entity.removeEffect = (effectId, opt) => {
56
+ if (!entity.effects[effectId])
57
+ return;
56
58
  clearTimeout(entity.effects[effectId].timeout);
57
59
  entity.effects[effectId] = null;
58
60
  entity.sendRemoveEffect(effectId, opt);
@@ -126,8 +126,9 @@ const server = function (serv, options) {
126
126
  client.end('Server is still starting! Please wait before reconnecting.');
127
127
  return;
128
128
  }
129
+ let player;
129
130
  try {
130
- const player = serv.initEntity('player', null, serv.overworld, new vec3_1.Vec3(0, 0, 0));
131
+ player = serv.initEntity('player', null, serv.overworld, new vec3_1.Vec3(0, 0, 0));
131
132
  Object.assign(player, assignProps);
132
133
  Object.defineProperty(player, 'position', {
133
134
  get() {
@@ -144,7 +145,8 @@ const server = function (serv, options) {
144
145
  return player;
145
146
  }
146
147
  catch (err) {
147
- setTimeout(() => { throw err; }, 0);
148
+ serv.emit('error', err, { type: 'playerLogin', player: player });
149
+ client.end(`Internal server error during login phase: ${err.message}`);
148
150
  }
149
151
  };
150
152
  serv._addPlayer = playerJoined;
@@ -1,11 +1,15 @@
1
1
  import { Vec3 } from 'vec3';
2
2
  export declare const server: (serv: Server) => void;
3
- export declare const player: (player: Player, serv: Server) => void;
3
+ export declare const player: (player: Player, serv: Server, { basePositionAntiCheat, logToChatPositionAntiCheat }: Options) => void;
4
4
  export type AABB = {
5
5
  min: Vec3;
6
6
  max: Vec3;
7
7
  };
8
8
  declare global {
9
+ interface Options {
10
+ basePositionAntiCheat?: boolean;
11
+ logToChatPositionAntiCheat?: boolean;
12
+ }
9
13
  interface Server {
10
14
  safeZones: AABB[];
11
15
  resetSafeZones: () => void;
@@ -4,7 +4,11 @@ exports.player = exports.server = void 0;
4
4
  const vec3_1 = require("vec3");
5
5
  // Module to make positions safe to move to.
6
6
  // If a client sends a position outside by more than threshold, ignore and teleport back inside.
7
+ // Also includes anti-cheat features for block collision and movement speed.
7
8
  const THRESHOLD = 0.5;
9
+ const PLAYER_SIZE = new vec3_1.Vec3(0.6, 1.8, 0.6); // Standard Minecraft player hitbox
10
+ const MAX_MOVEMENT_DISTANCE = 10; // Maximum blocks per tick movement (accounting for speed effects)
11
+ const BASE_WALKING_SPEED = 0.10000000149011612; // Base movement speed from playerDat.js
8
12
  const server = (serv) => {
9
13
  serv.safeZones ??= [];
10
14
  serv.resetSafeZones = () => {
@@ -17,12 +21,45 @@ const server = (serv) => {
17
21
  };
18
22
  };
19
23
  exports.server = server;
20
- const player = (player, serv) => {
24
+ const player = (player, serv, { basePositionAntiCheat = false, logToChatPositionAntiCheat = false }) => {
25
+ let lastMovementTime = Date.now();
26
+ let lastPosition;
27
+ player.onReady.then(() => {
28
+ lastPosition = player.position.clone();
29
+ });
21
30
  // Enforce safe areas on client-provided movement
22
31
  player.on('move_cancel', ({ position, onGround, teleport }, cancel) => {
23
32
  // Allow server teleports/moves to pass through
24
33
  if (teleport)
25
34
  return;
35
+ // Anti-cheat: Block collision detection
36
+ if (basePositionAntiCheat && isPlayerInsideBlock(player, serv, position)) {
37
+ cancel(false);
38
+ if (logToChatPositionAntiCheat) {
39
+ player.chat(`Position anti-cheat: Block collision detected. Teleporting to safe position.`);
40
+ }
41
+ player.teleport(findSafePosition(player, serv, position));
42
+ return;
43
+ }
44
+ // Anti-cheat: Movement speed limit
45
+ const currentTime = Date.now();
46
+ const deltaTime = (currentTime - lastMovementTime) / 1000; // Convert to seconds
47
+ if (basePositionAntiCheat && lastPosition && !teleport) {
48
+ const maxAllowedDistance = calculateMaxMovementDistance(player, deltaTime);
49
+ const distance = position.distanceTo(lastPosition);
50
+ if (distance > maxAllowedDistance) {
51
+ if (logToChatPositionAntiCheat) {
52
+ player.chat(`Position anti-cheat: Movement speed limit exceeded. Teleporting to safe position.`);
53
+ }
54
+ cancel(false);
55
+ player.teleport(lastPosition);
56
+ return;
57
+ }
58
+ }
59
+ // Update tracking for next movement
60
+ lastMovementTime = currentTime;
61
+ lastPosition = position.clone();
62
+ // Safe zones enforcement (original logic)
26
63
  const zones = serv.safeZones ?? [];
27
64
  if (zones.length === 0)
28
65
  return;
@@ -46,11 +83,103 @@ const player = (player, serv) => {
46
83
  // Otherwise, clamp back inside from direction of attempted position
47
84
  const corrected = clampToAABBFromDirection(position, zone);
48
85
  // Prevent default cancel handling and perform corrective teleport ourselves
86
+ if (logToChatPositionAntiCheat) {
87
+ player.chat(`Position anti-cheat: Out of bounds. Teleporting to safe position.`);
88
+ }
49
89
  cancel(false);
50
90
  player.teleport(corrected);
51
91
  });
52
92
  };
53
93
  exports.player = player;
94
+ // Anti-cheat helper functions
95
+ function isPlayerInsideBlock(player, serv, position) {
96
+ const blocks = serv.mcData.blocksByStateId;
97
+ const chunks = player.world.getColumns();
98
+ const chunk = chunks[position.x >> 4][position.z >> 4];
99
+ if (!chunk)
100
+ return false;
101
+ // Check collision points around player hitbox
102
+ const checkPositions = [
103
+ position, // Center
104
+ position.offset(PLAYER_SIZE.x / 2, 0, PLAYER_SIZE.z / 2), // Top-right corner
105
+ position.offset(-PLAYER_SIZE.x / 2, 0, PLAYER_SIZE.z / 2), // Top-left corner
106
+ position.offset(PLAYER_SIZE.x / 2, 0, -PLAYER_SIZE.z / 2), // Bottom-right corner
107
+ position.offset(-PLAYER_SIZE.x / 2, 0, -PLAYER_SIZE.z / 2), // Bottom-left corner
108
+ position.offset(0, PLAYER_SIZE.y / 2, 0), // Top center
109
+ position.offset(0, PLAYER_SIZE.y, 0) // Head position
110
+ ];
111
+ for (const checkPos of checkPositions) {
112
+ try {
113
+ const pos = new vec3_1.Vec3(Math.floor(checkPos.x) & 15, Math.floor(checkPos.y), Math.floor(checkPos.z) & 15);
114
+ const blockStateId = chunk.getBlockStateId(pos);
115
+ if (blocks[blockStateId]?.boundingBox === 'block') {
116
+ return true;
117
+ }
118
+ }
119
+ catch (error) {
120
+ // If we can't get block type, assume it's safe
121
+ continue;
122
+ }
123
+ }
124
+ return false;
125
+ }
126
+ function calculateMaxMovementDistance(player, deltaTime) {
127
+ let walkingSpeed = BASE_WALKING_SPEED;
128
+ // Apply speed effect if present (effect ID 1)
129
+ if (player.effects?.[1]) {
130
+ const amplifier = player.effects[1].amplifier || 0;
131
+ walkingSpeed = BASE_WALKING_SPEED * (1 + (amplifier + 1) * 0.2);
132
+ }
133
+ // For creative mode or flying, allow higher speed
134
+ if (player.gameMode === 1 || player.gameMode === 3 || player.flying) {
135
+ walkingSpeed *= 10; // Creative/spectator mode multiplier
136
+ }
137
+ // Convert to blocks per second and apply delta time, with maximum limit
138
+ const maxDistance = Math.min(walkingSpeed * 20 * deltaTime, MAX_MOVEMENT_DISTANCE);
139
+ return maxDistance;
140
+ }
141
+ function findSafePosition(player, serv, attemptedPosition) {
142
+ // Start from the attempted position and search nearby for a safe spot
143
+ const basePosition = attemptedPosition.floored();
144
+ const chunks = player.world.getColumns();
145
+ const chunk = chunks[basePosition.x >> 4][basePosition.z >> 4];
146
+ if (!chunk)
147
+ return basePosition;
148
+ // Search in expanding radius for a safe position
149
+ for (let radius = 0; radius <= 3; radius++) {
150
+ for (let x = -radius; x <= radius; x++) {
151
+ for (let z = -radius; z <= radius; z++) {
152
+ if (Math.abs(x) === radius || Math.abs(z) === radius) { // Only check edge positions for efficiency
153
+ const testPos = basePosition.offset(x, 0, z);
154
+ // Check if position is safe (not inside blocks)
155
+ let isSafe = true;
156
+ for (let y = 0; y < Math.ceil(PLAYER_SIZE.y); y++) {
157
+ const checkPos = testPos.offset(0, y, 0);
158
+ const pos = new vec3_1.Vec3(Math.floor(checkPos.x) & 15, Math.floor(checkPos.y), Math.floor(checkPos.z) & 15);
159
+ try {
160
+ const blockStateId = chunk.getBlockStateId(pos);
161
+ if (serv.mcData.blocksByStateId[blockStateId]?.boundingBox === 'block') {
162
+ isSafe = false;
163
+ break;
164
+ }
165
+ }
166
+ catch {
167
+ // If we can't check, assume unsafe
168
+ isSafe = false;
169
+ break;
170
+ }
171
+ }
172
+ if (isSafe) {
173
+ return testPos.offset(0.5, 0, 0.5); // Center in block
174
+ }
175
+ }
176
+ }
177
+ }
178
+ }
179
+ // If no safe position found, return player's current position
180
+ return player.position;
181
+ }
182
+ // Original helper functions
54
183
  function isInsideStrict(pos, box) {
55
184
  return pos.x >= box.min.x && pos.x <= box.max.x &&
56
185
  pos.y >= box.min.y && pos.y <= box.max.y &&
@@ -1,7 +1,33 @@
1
+ import { Vec3 } from 'vec3';
2
+ import { CustomWorld } from './world';
1
3
  export declare const server: (serv: Server) => void;
2
4
  export declare const player: (player: Player, serv: Server) => void;
3
5
  export declare const entity: (entity: Entity, serv: Server) => void;
6
+ interface SavedSound {
7
+ soundName: string;
8
+ soundCategory: number;
9
+ }
10
+ interface PlaySoundOptions {
11
+ whitelist?: any;
12
+ blacklist?: any[];
13
+ radius?: number;
14
+ volume?: number;
15
+ pitch?: number;
16
+ soundCategory?: number;
17
+ /** Optional ID to save the sound for later stopping */
18
+ saveId?: string;
19
+ /** Custom options to be added to sound name in parentheses as JSON */
20
+ customClientOptions?: Record<string, any>;
21
+ }
22
+ interface PlayNoteBlockOptions {
23
+ instrument?: string;
24
+ particle?: boolean;
25
+ }
4
26
  declare global {
27
+ interface Player {
28
+ /** Stores saved sounds by ID for later stopping */
29
+ savedSounds: Record<string, SavedSound>;
30
+ }
5
31
  interface Server {
6
32
  /** Plays `sound` (string, google "minecraft sound list") to all players in `opt.radius`.
7
33
  * If position is null, will play at the location of every player (taking into account whitelist and blacklist).
@@ -12,27 +38,24 @@ declare global {
12
38
  * - radius: Radius that sound can be heard (in fixed position so remember to multiply by 32, default 32*32)
13
39
  * - volume: float from 0-1 (default 1.0)
14
40
  * - pitch: float from 0.5 to 2 (default 1.0)
41
+ * - saveId: Optional ID to save the sound for later stopping
42
+ * - customClientOptions: Custom options to be added to sound name in parentheses as JSON
15
43
  */
16
- 'playSound': (sound: any, world: any, position: any, { whitelist, blacklist, radius, volume, pitch, soundCategory }?: {
17
- whitelist?: any;
18
- blacklist?: any[] | undefined;
19
- radius?: number | undefined;
20
- volume?: number | undefined;
21
- pitch?: number | undefined;
22
- soundCategory?: number | undefined;
23
- }) => void;
44
+ 'playSound': (sound: string, world: CustomWorld, position: Vec3 | null, opts?: PlaySoundOptions) => void;
24
45
  /** Plays noteblock in world at position. `pitch` is from 0-24 */
25
- "playNoteBlock": (pitch: any, world: any, position: any, { instrument, particle }?: {
26
- instrument?: string | undefined;
27
- particle?: boolean | undefined;
28
- }) => void;
46
+ "playNoteBlock": (pitch: number, world: CustomWorld, position: Vec3, opts?: PlayNoteBlockOptions) => void;
29
47
  /** Get pitch. `note` should be between 0-24 and your output is from 0.5 to 2.0 */
30
- "getNote": (note: any) => number;
48
+ "getNote": (note: number) => number;
49
+ /** Stop a previously saved sound by its ID */
50
+ "stopSound": (soundId: string) => void;
31
51
  }
32
52
  interface Player {
33
53
  /** Easy way to only play a sound for one player. Same opt as serv.playSound except no `whitelist`. */
34
- "playSound": (sound: any, opt?: {}) => void;
54
+ "playSound": (sound: string, opt?: PlaySoundOptions) => void;
55
+ /** Stop a specific sound by ID or all sounds if no ID provided */
56
+ "stopSound": (soundId?: string) => void;
35
57
  }
36
58
  interface Entity {
37
59
  }
38
60
  }
61
+ export {};
@@ -4,21 +4,36 @@ exports.entity = exports.player = exports.server = void 0;
4
4
  const utils_1 = require("../utils");
5
5
  const vec3_1 = require("vec3");
6
6
  const server = function (serv) {
7
- serv.playSound = (sound, world, position, { whitelist, blacklist = [], radius = 32, volume = 1.0, pitch = 1.0, soundCategory = 0 } = {}) => {
7
+ serv.playSound = (sound, world, position, { whitelist, blacklist = [], radius = 32, volume = 1.0, pitch = 1.0, soundCategory = 0, saveId, customClientOptions } = {}) => {
8
8
  const players = (typeof whitelist !== 'undefined'
9
9
  ? (whitelist instanceof Array ? whitelist : [whitelist])
10
10
  : serv.getNearby({
11
11
  world,
12
- position,
12
+ position: position,
13
13
  radius
14
14
  }));
15
+ // Add custom options to sound name if provided
16
+ let finalSoundName = sound;
17
+ if (customClientOptions) {
18
+ finalSoundName = `${sound}(${JSON.stringify(customClientOptions)})`;
19
+ }
20
+ // Save sound info if saveId provided for each player
21
+ if (saveId) {
22
+ const targetPlayers = players.filter(player => blacklist.indexOf(player) === -1);
23
+ targetPlayers.forEach(player => {
24
+ player.savedSounds[saveId] = {
25
+ soundName: sound,
26
+ soundCategory
27
+ };
28
+ });
29
+ }
15
30
  players.filter(player => blacklist.indexOf(player) === -1)
16
31
  .forEach(player => {
17
32
  const iniPos = position ? position.scaled(1 / 32) : player.position.scaled(1 / 32);
18
33
  const pos = iniPos.scaled(8).floored();
19
34
  // only packet still in fixed position in all versions
20
35
  player._client.write('named_sound_effect', {
21
- soundName: sound,
36
+ soundName: finalSoundName,
22
37
  soundCategory,
23
38
  x: pos.x,
24
39
  y: pos.y,
@@ -38,6 +53,22 @@ const server = function (serv) {
38
53
  serv.playSound('note.' + instrument, world, position, { pitch: serv.getNote(pitch) });
39
54
  };
40
55
  serv.getNote = note => 0.5 * Math.pow(Math.pow(2, 1 / 12), note);
56
+ serv.stopSound = (soundId, targetPlayers) => {
57
+ // If targetPlayers provided, stop sound only for them
58
+ // Otherwise stop for all players who have this sound saved
59
+ const players = targetPlayers || serv.players;
60
+ players.forEach(player => {
61
+ const soundInfo = player.savedSounds[soundId];
62
+ if (soundInfo) {
63
+ player._client.write('stop_sound', {
64
+ flags: 3, // Both source and sound
65
+ source: soundInfo.soundCategory,
66
+ sound: soundInfo.soundName
67
+ });
68
+ delete player.savedSounds[soundId];
69
+ }
70
+ });
71
+ };
41
72
  serv.commands.add({
42
73
  base: 'playsoundforall',
43
74
  info: 'to play sound for everyone',
@@ -83,9 +114,40 @@ const server = function (serv) {
83
114
  };
84
115
  exports.server = server;
85
116
  const player = function (player, serv) {
117
+ // Initialize player's saved sounds storage
118
+ player.savedSounds = {};
86
119
  player.playSound = (sound, opt = {}) => {
120
+ // If saveId is provided, store the sound in player's storage
121
+ if (opt.saveId) {
122
+ player.savedSounds[opt.saveId] = {
123
+ soundName: sound,
124
+ soundCategory: opt.soundCategory || 0
125
+ };
126
+ }
87
127
  serv.playSound(sound, player.world, null, { ...opt, whitelist: player });
88
128
  };
129
+ player.stopSound = (soundId) => {
130
+ if (soundId) {
131
+ // Stop specific sound if it exists in player's saved sounds
132
+ const soundInfo = player.savedSounds[soundId];
133
+ if (soundInfo) {
134
+ player._client.write('stop_sound', {
135
+ flags: 3, // Both source and sound
136
+ source: soundInfo.soundCategory,
137
+ sound: soundInfo.soundName
138
+ });
139
+ delete player.savedSounds[soundId];
140
+ }
141
+ }
142
+ else {
143
+ // Stop all sounds
144
+ player._client.write('stop_sound', {
145
+ flags: 0 // Stop all sounds
146
+ });
147
+ // Clear saved sounds storage
148
+ player.savedSounds = {};
149
+ }
150
+ };
89
151
  // player.on('placeBlock_cancel', async ({ reference }, cancel) => {
90
152
  // if (player.crouching) return
91
153
  // const id = await player.world.getBlockType(reference)
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.88",
4
+ "version": "0.0.90",
5
5
  "main": "dist/index.js",
6
6
  "types": "./dist/index.d.ts",
7
7
  "bin": "dist/app.js",