@zardoy/flying-squid 0.0.91 → 0.0.92

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.
@@ -1,2 +1,19 @@
1
- declare const _default: (obj: any) => (eventName: string, data?: any, func?: Function, cancelFunc?: Function) => Promise<any>;
1
+ export type CustomEventEmitter = {
2
+ emit(event: string, ...args: any[]): boolean;
3
+ emitThen(event: string, ...args: any[]): Promise<void>;
4
+ };
5
+ export type CancelFunction = (defaultCancel?: boolean, hidden?: boolean) => void;
6
+ export type BehaviorFunction<T = any, R = any> = (data: T) => R | Promise<R>;
7
+ export type BehaviorInputMap = {
8
+ [eventName: string]: {
9
+ _input: Record<string, any>;
10
+ };
11
+ };
12
+ export type MaybePromise<T> = T | Promise<T>;
13
+ export type BehaviorEventMap<M extends BehaviorInputMap, MK extends keyof M = keyof M> = {
14
+ [K in MK | `${MK & string}_cancel` | `${MK & string}_done`]: K extends `${MK & string}_cancel` ? (data: M[MK]['_input'], cancel: CancelFunction) => MaybePromise<void> : K extends `${MK & string}_done` ? (data: M[MK]['_input'], resp: any, cancelled: boolean) => MaybePromise<void> : (data: M[MK]['_input'], cancelled: boolean, cancelCount: number) => MaybePromise<void>;
15
+ };
16
+ export type BehaviorCallFunction<M extends BehaviorInputMap> = <E extends keyof M, D = M[E]['_input'], DF extends D = D, R = void>(eventName: E, data: D, func?: BehaviorFunction<DF, R>, cancelFunc?: BehaviorFunction<DF, R>) => Promise<BehaviorResult<R>>;
17
+ type BehaviorResult<R> = R extends void ? void : R;
18
+ declare const _default: (obj: CustomEventEmitter) => <D = any, DF extends D = D, R = void>(eventName: string, data: D, func?: BehaviorFunction<DF>, cancelFunc?: BehaviorFunction<DF>) => Promise<BehaviorResult<R>>;
2
19
  export default _default;
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.default = (obj) => {
4
- const handleError = (err, eventName) => {
4
+ const handleError = (err, eventName, canContinue) => {
5
5
  // Log the error but don't crash
6
6
  if (err.name === 'UserError') {
7
7
  obj.emit('error', err, 'behavior');
@@ -9,18 +9,22 @@ exports.default = (obj) => {
9
9
  else {
10
10
  const error = new Error(`Error in ${eventName} handler: ${err.message}`);
11
11
  error.stack = err.stack;
12
- obj.emit('error', error, 'behavior');
12
+ if (canContinue) {
13
+ obj.emit('error', error, 'behavior');
14
+ }
15
+ else {
16
+ throw error;
17
+ }
13
18
  }
14
- return false; // Return false to indicate error occurred
15
19
  };
16
- return async (eventName, data, func, cancelFunc) => {
17
- let hiddenCancelled = false;
20
+ const behavior = async (eventName, data, func = () => { }, cancelFunc = () => { }) => {
21
+ let hideEventCancel = false;
18
22
  let cancelled = false;
19
23
  let cancelCount = 0;
20
24
  let defaultCancel = true;
21
25
  const cancel = (dC = true, hidden = false) => {
22
26
  if (hidden)
23
- hiddenCancelled = true;
27
+ hideEventCancel = true;
24
28
  else {
25
29
  cancelled = true;
26
30
  cancelCount++;
@@ -28,21 +32,23 @@ exports.default = (obj) => {
28
32
  defaultCancel = dC;
29
33
  };
30
34
  let resp;
31
- func = func || (() => { });
32
35
  // Handle each event emission separately to allow pipeline to continue
36
+ // PRE EVENT
33
37
  try {
34
38
  await obj.emitThen(eventName + '_cancel', data, cancel);
35
39
  }
36
40
  catch (err) {
37
- handleError(err, eventName + '_cancel');
41
+ handleError(err, eventName + '_cancel', false);
38
42
  }
43
+ // MAIN EVENT
39
44
  try {
40
45
  await obj.emitThen(eventName, data, cancelled, cancelCount);
41
46
  }
42
47
  catch (err) {
43
- handleError(err, eventName);
48
+ handleError(err, eventName, false);
44
49
  }
45
- if (!hiddenCancelled && !cancelled) {
50
+ if (!hideEventCancel && !cancelled) {
51
+ // NOT CANCELLED, DEFAULT BEHAVIOR
46
52
  try {
47
53
  resp = func(data);
48
54
  if (resp instanceof Promise) {
@@ -52,11 +58,12 @@ exports.default = (obj) => {
52
58
  resp = true;
53
59
  }
54
60
  catch (err) {
55
- handleError(err, `${eventName} function`);
56
- resp = false;
61
+ handleError(err, `${eventName} function`, false);
62
+ // resp = false
57
63
  }
58
64
  }
59
65
  else if (cancelFunc && defaultCancel) {
66
+ // CANCELLED, DEFAULT BEHAVIOR
60
67
  try {
61
68
  resp = cancelFunc(data);
62
69
  if (resp instanceof Promise) {
@@ -66,16 +73,18 @@ exports.default = (obj) => {
66
73
  resp = false;
67
74
  }
68
75
  catch (err) {
69
- handleError(err, `${eventName} cancel function`);
70
- resp = false;
76
+ handleError(err, `${eventName} cancel function`, false);
77
+ // resp = false
71
78
  }
72
79
  }
80
+ // POST EVENT
73
81
  try {
74
- await obj.emitThen(eventName + '_done', data, cancelled);
82
+ await obj.emitThen(eventName + '_done', data, resp, cancelled);
75
83
  }
76
84
  catch (err) {
77
- handleError(err, eventName + '_done');
85
+ handleError(err, eventName + '_done', true);
78
86
  }
79
87
  return resp;
80
88
  };
89
+ return behavior;
81
90
  };
@@ -1,3 +1,8 @@
1
1
  export declare const player: (player: Player) => void;
2
2
  declare global {
3
+ interface PlayerBehaviorInputMap {
4
+ 'armSwing': {
5
+ _input: {};
6
+ };
7
+ }
3
8
  }
@@ -2,7 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.player = void 0;
4
4
  const player = function (player) {
5
- player._client.on('arm_animation', () => player.behavior('punch', {}, () => {
5
+ player._client.on('arm_animation', () => player.behavior('armSwing', {}, () => {
6
6
  player._writeOthersNearby('animation', {
7
7
  entityId: player.id,
8
8
  animation: 0
@@ -1,4 +1,4 @@
1
- import Behavior from '../behavior';
1
+ import Behavior, { BehaviorCallFunction } from '../behavior';
2
2
  export declare const server: (serv: Server) => void;
3
3
  export declare const entity: (entity: any) => void;
4
4
  declare global {
@@ -8,4 +8,9 @@ declare global {
8
8
  interface Entity {
9
9
  behavior: ReturnType<typeof Behavior>;
10
10
  }
11
+ interface Player {
12
+ behavior: BehaviorCallFunction<{
13
+ [K in keyof PlayerBehaviorInputMap]: PlayerBehaviorInputMap[K];
14
+ }>;
15
+ }
11
16
  }
@@ -30,4 +30,19 @@ declare global {
30
30
  */
31
31
  'setBlockAction': (position: Vec3, actionId: number, actionParam: number) => any;
32
32
  }
33
+ interface PlayerBehaviorInputMap {
34
+ 'sendBlock': {
35
+ _input: {
36
+ position: Vec3;
37
+ };
38
+ };
39
+ 'sendBlockAction': {
40
+ _input: {
41
+ position: Vec3;
42
+ actionId: number;
43
+ actionParam: number;
44
+ blockType: number;
45
+ };
46
+ };
47
+ }
33
48
  }
@@ -44,4 +44,20 @@ declare global {
44
44
  /** sends `message` to the player */
45
45
  "chat": (message: any) => void;
46
46
  }
47
+ interface PlayerBehaviorInputMap {
48
+ 'command': {
49
+ _input: {
50
+ command: string;
51
+ };
52
+ };
53
+ 'chat': {
54
+ _input: {
55
+ message: string;
56
+ prefix: string;
57
+ text: string;
58
+ whitelist: Player[];
59
+ blacklist: Player[];
60
+ };
61
+ };
62
+ }
47
63
  }
@@ -5,6 +5,7 @@ export type BreakTimeConfig = {
5
5
  toolNames: string[];
6
6
  blocks: {
7
7
  [stateId: number]: number;
8
+ '*'?: number;
8
9
  };
9
10
  };
10
11
  declare global {
@@ -45,7 +45,7 @@ const player = async (player, serv) => {
45
45
  if (config.toolNames.length > 0 && !config.toolNames.includes(heldItemName ?? '')) {
46
46
  return undefined;
47
47
  }
48
- return config.blocks?.[block.type] ?? config.blocks?.['*'];
48
+ return config.blocks?.[block.stateId] ?? config.blocks?.['*'];
49
49
  };
50
50
  // Register the channel
51
51
  player._client.registerChannel(CHANNEL_NAME, ['container', [
@@ -161,11 +161,7 @@ const player = function (player, serv, options) {
161
161
  await serv.savePlayerDataToDisk(player.uuid);
162
162
  });
163
163
  // Count placed blocks attempts
164
- let lastPlace = 0;
165
164
  player.on('blockPlaced', () => {
166
- if (Date.now() - lastPlace < 5)
167
- return;
168
- lastPlace = Date.now();
169
165
  const store = serv.getPlayerData(player.uuid);
170
166
  store.stats.totalPlacedBlocks += 1;
171
167
  serv.updatePlayerData(player.uuid, store);
@@ -1,3 +1,45 @@
1
+ import { Vec3 } from 'vec3';
2
+ import { Block } from 'prismarine-block';
3
+ import { CustomWorld } from './world';
1
4
  export declare const player: (player: Player, serv: Server, { version }: Options) => void;
2
5
  declare global {
6
+ interface PlayerBehaviorInputMap {
7
+ 'item_drop': {
8
+ _input: {
9
+ blockDropPosition: Vec3;
10
+ blockDropWorld: CustomWorld;
11
+ blockDropVelocity: Vec3;
12
+ blockDropId: number;
13
+ blockDropDamage: number;
14
+ blockDropCount: number;
15
+ blockDropPickup: number;
16
+ blockDropDeath: number;
17
+ };
18
+ };
19
+ 'breakAnimation': {
20
+ _input: {
21
+ lastState: number;
22
+ state: number;
23
+ start: () => void;
24
+ timePassed: number;
25
+ position: Vec3;
26
+ };
27
+ };
28
+ 'dug': {
29
+ _input: {
30
+ position: Vec3;
31
+ block: Block;
32
+ dropBlock: boolean;
33
+ drops: any[];
34
+ directionVector: Vec3;
35
+ };
36
+ };
37
+ 'suspiciousDigStopped': {
38
+ _input: {
39
+ tooFast: boolean;
40
+ tooFar: boolean;
41
+ location: Vec3;
42
+ };
43
+ };
44
+ }
3
45
  }
@@ -53,14 +53,14 @@ const player = function (player, serv, { version }) {
53
53
  console.warn(`[Digging] Column not loaded for player ${player.username} at ${pos}`);
54
54
  return;
55
55
  }
56
- const facedBlock = columnFaced.getBlock(new vec3_1.Vec3(facedPos.x & 15, 0, facedPos.z & 15));
56
+ const facedBlock = columnFaced.getBlock(new vec3_1.Vec3(facedPos.x & 15, facedPos.y, facedPos.z & 15));
57
57
  let block;
58
58
  if (facedBlock.name === 'fire') {
59
59
  block = facedBlock;
60
60
  pos = facedPos;
61
61
  }
62
62
  else {
63
- block = columnBlock.getBlock(new vec3_1.Vec3(pos.x & 15, 0, pos.z & 15));
63
+ block = columnBlock.getBlock(new vec3_1.Vec3(pos.x & 15, pos.y, pos.z & 15));
64
64
  }
65
65
  currentlyDugBlock = block;
66
66
  if (currentlyDugBlock.type === 0)
@@ -155,13 +155,17 @@ const player = function (player, serv, { version }) {
155
155
  let stop = false;
156
156
  // const MAX_DIG_DISTANCE = 7
157
157
  const MAX_DIG_DISTANCE = 8;
158
- if (expectedDiggingTime - diggingTime < 100 && player.position.distanceTo(location) > MAX_DIG_DISTANCE) {
159
- stop = player.behavior('forceCancelDig', {
160
- stop: true,
161
- start: startDiggingTime,
162
- time: diggingTime
163
- //@ts-ignore todo
164
- }).stop;
158
+ const tooFast = expectedDiggingTime - diggingTime > 50;
159
+ const tooFar = player.position.distanceTo(location) > MAX_DIG_DISTANCE;
160
+ if (tooFast || tooFar) {
161
+ stop = true;
162
+ await player.behavior('suspiciousDigStopped', {
163
+ tooFast,
164
+ tooFar,
165
+ location
166
+ }, () => { }, () => {
167
+ stop = false;
168
+ });
165
169
  }
166
170
  if (!stop) {
167
171
  const drops = [];
@@ -225,7 +229,7 @@ const player = function (player, serv, { version }) {
225
229
  else {
226
230
  player._client.write('block_change', {
227
231
  location,
228
- type: currentlyDugBlock.type << 4
232
+ type: currentlyDugBlock.stateId
229
233
  });
230
234
  if (serv.supportFeature('acknowledgePlayerDigging')) {
231
235
  player.writePacket('acknowledge_player_digging', {
@@ -252,6 +256,7 @@ const player = function (player, serv, { version }) {
252
256
  position: location,
253
257
  block: currentlyDugBlock,
254
258
  dropBlock: false,
259
+ blockDropCount: 0,
255
260
  blockDropPosition: location.offset(0.5, 0.5, 0.5),
256
261
  blockDropWorld: player.world,
257
262
  blockDropVelocity: blockDropVelocity,
@@ -1,13 +1,38 @@
1
1
  import { Block } from 'prismarine-block';
2
+ import { Vec3 } from 'vec3';
3
+ import { Item } from 'prismarine-item';
2
4
  export declare const server: (serv: Server, { version }: Options) => void;
3
5
  export declare const player: (player: Player, serv: Server, { version }: Options) => void;
6
+ type MaybePromise<T> = T | Promise<T>;
4
7
  declare global {
5
8
  interface Server {
6
9
  /** Register a handler that will be called when an item of type `name` is called to place a block.
7
10
  *
8
11
  * The argument given to the handler is an object containing the held item that triggered the event, the direction (face) on which the player clicked, the angle of the player around the placed block. It should return an object containing the id and data of the block to place.
9
12
  */
10
- 'onItemPlace': (name: any, handler: any, warn?: boolean) => void;
13
+ 'onItemPlace': (name: string, handler: (data: {
14
+ item: Item;
15
+ direction: number;
16
+ angle: number;
17
+ player: Player;
18
+ referencePosition: Vec3;
19
+ placedPosition: Vec3;
20
+ directionVector: Vec3;
21
+ properties: any;
22
+ }) => MaybePromise<{
23
+ id: number;
24
+ data: number;
25
+ } | void>, warn?: boolean) => void;
26
+ 'onItemUse': (name: string, handler: (data: {
27
+ item: Item;
28
+ slot: number;
29
+ player: Player;
30
+ }) => void) => void;
31
+ itemUseHandlers: Map<number, (data: {
32
+ item: Item;
33
+ slot: number;
34
+ player: Player;
35
+ }) => void>;
11
36
  /** Register a handler that will be called when a player interact with a block of type `name`.
12
37
  *
13
38
  * The argument given to the handler is an object containing the clicked block and the player. It should return true if the block interaction occurred and the block placement should be cancelled.
@@ -18,3 +43,4 @@ declare global {
18
43
  }) => boolean | Promise<boolean>) => void;
19
44
  }
20
45
  }
46
+ export {};
@@ -35,6 +35,15 @@ const server = (serv, { version }) => {
35
35
  }
36
36
  itemPlaceHandlers.set(item.id, handler);
37
37
  };
38
+ serv.itemUseHandlers = new Map();
39
+ serv.onItemUse = (name, handler) => {
40
+ const item = mcData.itemsByName[name] ?? mcData.blocksByName[name];
41
+ if (!item) {
42
+ serv.warn(`[onItemUse] Unknown item or block ${name}`);
43
+ return;
44
+ }
45
+ serv.itemUseHandlers.set(item.id, handler);
46
+ };
38
47
  if (serv.supportFeature('theFlattening')) {
39
48
  const parseValue = (value, state) => {
40
49
  if (state.type === 'enum') {
@@ -140,7 +149,13 @@ exports.server = server;
140
149
  const player = function (player, serv, { version }) {
141
150
  const mcData = serv.mcData;
142
151
  const blocks = mcData.blocks;
143
- player._client.on('block_place', async ({ direction, location, cursorY } = {}) => {
152
+ let lastPlace = 0;
153
+ player._client.on('block_place', async ({ direction, location, cursorY, hand = 0 }) => {
154
+ if (hand !== 0)
155
+ return; // todo-low implement offhand
156
+ if (Date.now() - lastPlace < 15)
157
+ return;
158
+ lastPlace = Date.now();
144
159
  const referencePosition = new vec3_1.Vec3(location.x, location.y, location.z);
145
160
  const block = await player.world.getBlock(referencePosition);
146
161
  block.position = referencePosition;
@@ -192,7 +207,7 @@ const player = function (player, serv, { version }) {
192
207
  half,
193
208
  waterlogged: (await player.world.getBlock(placedPosition)).type === mcData.blocksByName.water.id
194
209
  }
195
- });
210
+ }) ?? {};
196
211
  if (!blocks[id])
197
212
  return;
198
213
  player.emit('blockPlaced', blocks[id]);
@@ -212,6 +227,19 @@ const player = function (player, serv, { version }) {
212
227
  const stateId = serv.supportFeature('theFlattening') ? (blocks[id].minStateId + data) : (id << 4 | data);
213
228
  player.setBlock(placedPosition, stateId);
214
229
  });
230
+ let lastItemUse = 0;
231
+ player._client.on('use_item', async ({ hand = 0 }) => {
232
+ if (Date.now() - lastItemUse < 15)
233
+ return;
234
+ lastItemUse = Date.now();
235
+ const heldItem = player.inventory.slots[hand === 0 ? 36 + player.heldItemSlot : 45];
236
+ if (!heldItem || heldItem.type === -1)
237
+ return;
238
+ const handler = serv.itemUseHandlers.get(heldItem.type);
239
+ if (handler) {
240
+ handler({ item: heldItem, slot: hand === 0 ? player.heldItemSlot : 45, player });
241
+ }
242
+ });
215
243
  };
216
244
  exports.player = player;
217
245
  const directionToVector = [new vec3_1.Vec3(0, -1, 0), new vec3_1.Vec3(0, 1, 0), new vec3_1.Vec3(0, 0, -1), new vec3_1.Vec3(0, 0, 1), new vec3_1.Vec3(-1, 0, 0), new vec3_1.Vec3(1, 0, 0)];
@@ -106,6 +106,9 @@ const server = function (serv, options) {
106
106
  plugin.player?.(player, serv, options);
107
107
  serv.emit('newPlayer', player);
108
108
  player.emit('asap');
109
+ player.on('move', () => {
110
+ player.sendChunkWhenMove();
111
+ });
109
112
  };
110
113
  // #region hot reload
111
114
  serv.on('pluginsReady', () => {
@@ -113,7 +116,6 @@ const server = function (serv, options) {
113
116
  for (const player of serv.players ?? []) {
114
117
  addPlayerShared(player);
115
118
  player.world = serv.overworld;
116
- player.sendChunkWhenMove();
117
119
  player._unloadAllChunks();
118
120
  player.sendRestMap();
119
121
  }
@@ -286,26 +288,28 @@ const player = async function (player, serv, settings) {
286
288
  return new vec3_1.Vec3(pos.x, 0, pos.z);
287
289
  };
288
290
  player.sendChunkWhenMove = () => {
289
- player.on('move', () => {
290
- if (player.stopChunkUpdates)
291
- return;
292
- if (getXYPos(player.position).distanceTo(getXYPos(player.lastPositionChunkUpdated)) > 16) {
293
- player.sendRestMap();
294
- }
295
- if (!serv.supportFeature('updateViewPosition')) {
296
- return;
297
- }
298
- const chunkX = Math.floor(player.position.x / 16);
299
- const chunkZ = Math.floor(player.position.z / 16);
300
- const lastChunkX = Math.floor(player.lastPositionPlayersUpdated.x / 16);
301
- const lastChunkZ = Math.floor(player.lastPositionPlayersUpdated.z / 16);
302
- if (chunkX !== lastChunkX || chunkZ !== lastChunkZ) {
303
- player._client.write('update_view_position', {
304
- chunkX,
305
- chunkZ
306
- });
307
- }
308
- });
291
+ if (player.stopChunkUpdates) {
292
+ return;
293
+ }
294
+ if (!player.lastPositionChunkUpdated) {
295
+ return;
296
+ }
297
+ if (getXYPos(player.position).distanceTo(getXYPos(player.lastPositionChunkUpdated)) > 16) {
298
+ player.sendRestMap();
299
+ }
300
+ if (!serv.supportFeature('updateViewPosition')) {
301
+ return;
302
+ }
303
+ const chunkX = Math.floor(player.position.x / 16);
304
+ const chunkZ = Math.floor(player.position.z / 16);
305
+ const lastChunkX = Math.floor(player.lastPositionPlayersUpdated.x / 16);
306
+ const lastChunkZ = Math.floor(player.lastPositionPlayersUpdated.z / 16);
307
+ if (chunkX !== lastChunkX || chunkZ !== lastChunkZ) {
308
+ player._client.write('update_view_position', {
309
+ chunkX,
310
+ chunkZ
311
+ });
312
+ }
309
313
  };
310
314
  function updateTime() {
311
315
  player._client.write('update_time', {
@@ -471,7 +475,6 @@ const player = async function (player, serv, settings) {
471
475
  await player.waitPlayerLogin();
472
476
  }
473
477
  player.sendRestMap();
474
- player.sendChunkWhenMove();
475
478
  if (playerData.new) { // otherwise we skip unnecessary fs operation
476
479
  player.save();
477
480
  }
@@ -1,7 +1,12 @@
1
+ import { Vec3 } from 'vec3';
1
2
  export declare const player: (player: Player, serv: Server) => void;
2
3
  export declare const entity: (entity: Entity, serv: Server) => void;
3
4
  export declare const server: (serv: Server) => void;
4
5
  declare global {
6
+ interface Player {
7
+ /** Timestamp of last damage taken, used for movement anti-cheat */
8
+ lastDamageTime?: number;
9
+ }
5
10
  interface Entity {
6
11
  /** Whether the entity is invincible to all damage */
7
12
  invincible: boolean;
@@ -21,4 +26,12 @@ declare global {
21
26
  animation?: boolean | undefined;
22
27
  }) => void;
23
28
  }
29
+ interface PlayerBehaviorInputMap {
30
+ 'attack': {
31
+ _input: {
32
+ attackedEntity: Entity;
33
+ velocity: Vec3;
34
+ };
35
+ };
36
+ }
24
37
  }
@@ -61,6 +61,10 @@ const entity = function (entity, serv) {
61
61
  return;
62
62
  entity.updateHealth(entity.health - damage);
63
63
  serv.playSound(sound, entity.world, entity.position);
64
+ // Track last damage time for anti-cheat movement checks
65
+ if (entity.type === 'player') {
66
+ entity.lastDamageTime = Date.now();
67
+ }
64
68
  entity.sendVelocity(velocity, maxVelocity);
65
69
  if (entity.health <= 0) {
66
70
  if (animation) {
@@ -1,3 +1,11 @@
1
1
  export declare const player: (player: Player, serv: Server) => void;
2
2
  declare global {
3
+ interface PlayerBehaviorInputMap {
4
+ 'requestRespawn': {
5
+ _input: {
6
+ previousGameMode: number;
7
+ dimension: number;
8
+ };
9
+ };
10
+ }
3
11
  }
@@ -1,6 +1,6 @@
1
1
  import { Vec3 } from 'vec3';
2
2
  export declare const server: (serv: Server) => void;
3
- export declare const player: (player: Player, serv: Server, { basePositionAntiCheat, logToChatPositionAntiCheat }: Options) => void;
3
+ export declare const player: (player: Player, serv: Server, { basePositionAntiCheat, positionAntiCheatNotifyPlayer }: Options) => void;
4
4
  export type AABB = {
5
5
  min: Vec3;
6
6
  max: Vec3;
@@ -8,7 +8,7 @@ export type AABB = {
8
8
  declare global {
9
9
  interface Options {
10
10
  basePositionAntiCheat?: boolean;
11
- logToChatPositionAntiCheat?: boolean;
11
+ positionAntiCheatNotifyPlayer?: boolean;
12
12
  }
13
13
  interface Server {
14
14
  safeZones: AABB[];
@@ -7,8 +7,11 @@ const vec3_1 = require("vec3");
7
7
  // Also includes anti-cheat features for block collision and movement speed.
8
8
  const THRESHOLD = 0.5;
9
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
10
+ // Vanilla-like movement validation constants (from ServerGamePacketListenerImpl.java)
11
+ const VANILLA_SPEED_LIMIT_NORMAL = 100.0; // Normal movement limit (squared distance)
12
+ const VANILLA_SPEED_LIMIT_FLYING = 300.0; // Elytra/flying limit (squared distance)
13
+ const KNOCKBACK_VELOCITY = 8; // From pvp.ts KNOCKBACK_MULTIPLIER
14
+ const KNOCKBACK_GRACE_PERIOD = 2000; // Allow higher speed for 2 seconds after damage
12
15
  const server = (serv) => {
13
16
  serv.safeZones ??= [];
14
17
  serv.resetSafeZones = () => {
@@ -21,44 +24,66 @@ const server = (serv) => {
21
24
  };
22
25
  };
23
26
  exports.server = server;
24
- const player = (player, serv, { basePositionAntiCheat = false, logToChatPositionAntiCheat = false }) => {
27
+ const player = (player, serv, { basePositionAntiCheat = false, positionAntiCheatNotifyPlayer = false }) => {
25
28
  let lastMovementTime = Date.now();
26
- let lastPosition;
29
+ let packetCount = 0; // Track move packets per tick (vanilla approach)
30
+ serv.on('tick', (deltaTime, tickCount) => {
31
+ packetCount = 0;
32
+ });
27
33
  player.onReady.then(() => {
28
- lastPosition = player.position.clone();
34
+ player.knownPosition ??= player.position.clone();
29
35
  });
30
36
  // Enforce safe areas on client-provided movement
31
37
  player.on('move_cancel', ({ position, onGround, teleport }, cancel) => {
38
+ const lastPosition = player.knownPosition;
32
39
  // Allow server teleports/moves to pass through
33
- if (teleport)
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
+ const currentTime = Date.now();
41
+ // Check if this is a response to our teleport
42
+ if (player.pendingTeleport) {
43
+ if (position.distanceTo(player.pendingTeleport) < 0.1) {
44
+ lastMovementTime = currentTime;
45
+ player.knownPosition = position.clone();
46
+ player.pendingTeleport = null;
40
47
  }
41
- player.teleport(findSafePosition(player, serv, position));
42
48
  return;
43
49
  }
44
- // Anti-cheat: Movement speed limit
45
- const currentTime = Date.now();
50
+ // Allow server teleports
51
+ if (teleport) {
52
+ lastMovementTime = currentTime;
53
+ return;
54
+ }
46
55
  const deltaTime = (currentTime - lastMovementTime) / 1000; // Convert to seconds
56
+ lastMovementTime = currentTime;
57
+ // Anti-cheat: Block collision detection
58
+ // if (basePositionAntiCheat && isPlayerInsideBlock(player, serv, position)) {
59
+ // cancel(false)
60
+ // if (positionAntiCheatNotifyPlayer) {
61
+ // player.chat(`[safeZones] Block collision detected. Teleporting to safe position.`)
62
+ // }
63
+ // player.teleport(lastPosition ?? findSafePosition(player, serv, position))
64
+ // return
65
+ // }
66
+ // Anti-cheat: Movement speed limit (vanilla-like approach)
47
67
  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.`);
68
+ packetCount++;
69
+ // Limit packet count per tick like vanilla (max 5 meaningful packets)
70
+ if (packetCount > 5) {
71
+ packetCount = 1;
72
+ }
73
+ const speedCheck = validateMovementSpeed(player, lastPosition, position, packetCount);
74
+ if (!speedCheck.isValid) {
75
+ if (positionAntiCheatNotifyPlayer) {
76
+ player.chat(`[safeZones] ${speedCheck.reason} ` +
77
+ `(distance²=${speedCheck.distanceSquared.toFixed(2)}, ` +
78
+ `limit=${speedCheck.speedLimit.toFixed(2)}, ` +
79
+ `velocity²=${speedCheck.currentVelocitySquared.toFixed(2)})`);
53
80
  }
54
81
  cancel(false);
55
82
  player.teleport(lastPosition);
56
83
  return;
57
84
  }
58
85
  }
59
- // Update tracking for next movement
60
- lastMovementTime = currentTime;
61
- lastPosition = position.clone();
86
+ // lastPosition = position.clone()
62
87
  // Safe zones enforcement (original logic)
63
88
  const zones = serv.safeZones ?? [];
64
89
  if (zones.length === 0)
@@ -83,8 +108,8 @@ const player = (player, serv, { basePositionAntiCheat = false, logToChatPosition
83
108
  // Otherwise, clamp back inside from direction of attempted position
84
109
  const corrected = clampToAABBFromDirection(position, zone);
85
110
  // 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.`);
111
+ if (positionAntiCheatNotifyPlayer) {
112
+ player.chat(`[safeZones] Out of bounds. Teleporting to safe position.`);
88
113
  }
89
114
  cancel(false);
90
115
  player.teleport(corrected);
@@ -94,8 +119,7 @@ exports.player = player;
94
119
  // Anti-cheat helper functions
95
120
  function isPlayerInsideBlock(player, serv, position) {
96
121
  const blocks = serv.mcData.blocksByStateId;
97
- const chunks = player.world.getColumns();
98
- const chunk = chunks[position.x >> 4][position.z >> 4];
122
+ const chunk = player.world.getLoadedColumnAt(position);
99
123
  if (!chunk)
100
124
  return false;
101
125
  // Check collision points around player hitbox
@@ -123,20 +147,56 @@ function isPlayerInsideBlock(player, serv, position) {
123
147
  }
124
148
  return false;
125
149
  }
126
- function calculateMaxMovementDistance(player, deltaTime) {
127
- let walkingSpeed = BASE_WALKING_SPEED;
128
- // Apply speed effect if present (effect ID 1)
150
+ function validateMovementSpeed(player, lastPosition, newPosition, packetCount) {
151
+ // Calculate movement delta (like vanilla)
152
+ const deltaX = newPosition.x - lastPosition.x;
153
+ const deltaY = newPosition.y - lastPosition.y;
154
+ const deltaZ = newPosition.z - lastPosition.z;
155
+ // Calculate squared distance moved (vanilla approach for efficiency)
156
+ const distanceSquared = deltaX * deltaX + deltaY * deltaY + deltaZ * deltaZ;
157
+ // Get player's current velocity squared (would be from entity.getDeltaMovement().lengthSqr() in vanilla)
158
+ // Since we don't track this exactly, we'll use a reasonable estimate
159
+ // Vanilla subtracts current velocity from distance to allow for momentum
160
+ // We'll use a moderate estimate to allow for normal sprinting movement
161
+ const estimatedVelocitySquared = Math.min(distanceSquared * 0.6, 50); // Allow some momentum, capped
162
+ // Determine speed limit based on player state
163
+ let speedLimit = VANILLA_SPEED_LIMIT_NORMAL;
164
+ let mode = 'walking';
165
+ // Assume player is always sprinting (as requested) - increases speed by ~30%
166
+ // Sprinting in vanilla increases movement by 1.3x, so squared distance by 1.69x
167
+ speedLimit *= 1.69; // 1.3^2 for sprinting
168
+ mode = 'sprinting';
169
+ // Check if player is flying/creative (higher limit)
170
+ if (player.gameMode === 1 || player.gameMode === 3 || player.flying) {
171
+ speedLimit = VANILLA_SPEED_LIMIT_FLYING * 1.69; // Also apply sprinting to creative
172
+ mode = 'creative/flying+sprint';
173
+ }
174
+ // Apply speed effect multiplier if present (effect ID 1 = speed)
129
175
  if (player.effects?.[1]) {
130
176
  const amplifier = player.effects[1].amplifier || 0;
131
- walkingSpeed = BASE_WALKING_SPEED * (1 + (amplifier + 1) * 0.2);
177
+ const speedMultiplier = 1 + (amplifier + 1) * 0.2;
178
+ speedLimit *= speedMultiplier * speedMultiplier; // Square it since we're comparing squared distances
179
+ mode = `speed ${amplifier}`;
132
180
  }
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
181
+ // Check if player was recently damaged (allow higher speed for knockback)
182
+ const now = Date.now();
183
+ const lastDamageTime = player.lastDamageTime || 0;
184
+ if (now - lastDamageTime < KNOCKBACK_GRACE_PERIOD) {
185
+ speedLimit = Math.max(speedLimit, KNOCKBACK_VELOCITY * KNOCKBACK_VELOCITY * 4); // Very generous for knockback
186
+ mode = 'knockback';
136
187
  }
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;
188
+ // Apply packet count multiplier (vanilla does this)
189
+ const adjustedLimit = speedLimit * packetCount;
190
+ // Vanilla check: distanceSquared - currentVelocitySquared > limit
191
+ const excessMovement = distanceSquared - estimatedVelocitySquared;
192
+ const isValid = excessMovement <= adjustedLimit;
193
+ return {
194
+ isValid,
195
+ reason: isValid ? 'valid' : `Movement too fast (${mode})`,
196
+ distanceSquared,
197
+ speedLimit: adjustedLimit,
198
+ currentVelocitySquared: estimatedVelocitySquared
199
+ };
140
200
  }
141
201
  function findSafePosition(player, serv, attemptedPosition) {
142
202
  // Start from the attempted position and search nearby for a safe spot
@@ -4,6 +4,8 @@ export declare const entity: (entity: Entity, serv: Server) => void;
4
4
  declare global {
5
5
  interface Player {
6
6
  "sendAbilities": () => void;
7
+ /** Position we're expecting the client to move to after teleport */
8
+ pendingTeleport?: Vec3 | null;
7
9
  }
8
10
  interface Entity {
9
11
  /** ID of entity on server */
@@ -18,4 +20,20 @@ declare global {
18
20
  pitch: number;
19
21
  "teleport": (pos: Vec3) => void;
20
22
  }
23
+ interface PlayerBehaviorInputMap {
24
+ 'move': {
25
+ _input: {
26
+ position: Vec3;
27
+ onGround: boolean;
28
+ teleport: boolean;
29
+ };
30
+ };
31
+ 'look': {
32
+ _input: {
33
+ yaw: number;
34
+ pitch: number;
35
+ onGround: boolean;
36
+ };
37
+ };
38
+ }
21
39
  }
@@ -68,12 +68,24 @@ const player = function (player) {
68
68
  teleportId: 1
69
69
  });
70
70
  if (sendChunks)
71
- player.emit('move');
71
+ player.sendChunkWhenMove();
72
72
  };
73
+ let oldSetTimeout;
73
74
  player.teleport = async (position) => {
75
+ // Track pending teleport for anti-cheat
76
+ if (oldSetTimeout)
77
+ clearTimeout(oldSetTimeout);
78
+ player.pendingTeleport = position.clone();
74
79
  const notCancelled = await player.sendPosition(position, false, true);
75
- if (notCancelled)
76
- player.sendSelfPosition();
80
+ if (!notCancelled)
81
+ return;
82
+ 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
77
89
  };
78
90
  player.sendAbilities = () => {
79
91
  const isInvulnerable = player.gameMode === 1 || player.gameMode === 3; // Creative or Spectator
@@ -98,12 +110,13 @@ const player = function (player) {
98
110
  };
99
111
  exports.player = player;
100
112
  const entity = function (entity, serv) {
101
- entity.sendPosition = (position, onGround, teleport = false) => {
113
+ entity.sendPosition = async (position, onGround, teleport = false) => {
102
114
  if (typeof position === 'undefined')
103
- throw new Error('undef');
115
+ throw new Error('position is undefined');
104
116
  if (entity.position.equals(position) && entity.onGround === onGround)
105
- return Promise.resolve();
106
- return entity.behavior('move', {
117
+ return true;
118
+ let cancelled = false;
119
+ await entity.behavior('move', {
107
120
  position,
108
121
  onGround,
109
122
  teleport
@@ -161,9 +174,11 @@ const entity = function (entity, serv) {
161
174
  entity.position = position;
162
175
  entity.onGround = onGround;
163
176
  }, () => {
177
+ cancelled = true;
164
178
  if (entity.type === 'player')
165
179
  entity.sendSelfPosition();
166
180
  });
181
+ return !cancelled;
167
182
  };
168
183
  entity.teleport = (pos) => {
169
184
  entity.sendPosition(pos, false, true);
@@ -33,7 +33,7 @@ const server = (serv, { version }) => {
33
33
  else {
34
34
  if (serv.supportFeature('entityMCPrefixed')) { // 1.12 support
35
35
  serv.onItemPlace('spawn_egg', ({ item, player, placedPosition }) => {
36
- serv.spawnMob(getEntID(item.nbt.value.EntityTag.value.id.value), player.world, placedPosition);
36
+ serv.spawnMob(getEntID(item.nbt?.value?.EntityTag?.value?.id?.value), player.world, placedPosition);
37
37
  return { id: -1, data: 0 };
38
38
  });
39
39
  }
@@ -46,7 +46,7 @@ const server = (serv, { version }) => {
46
46
  }
47
47
  else {
48
48
  serv.onItemPlace('spawn_egg', ({ item, player, placedPosition }) => {
49
- serv.spawnMob(getEntID('minecraft:' + item.nbt.value.EntityTag.value.id.value), player.world, placedPosition);
49
+ serv.spawnMob(getEntID('minecraft:' + item.nbt?.value?.EntityTag?.value?.id?.value), player.world, placedPosition);
50
50
  return { id: -1, data: 0 };
51
51
  });
52
52
  }
@@ -1,4 +1,4 @@
1
- import { World } from 'prismarine-world/types/world';
1
+ import { Chunk, World } from 'prismarine-world/types/world';
2
2
  import { LevelDatFull } from 'prismarine-provider-anvil/src/level';
3
3
  import { Vec3 } from 'vec3';
4
4
  export declare const server: ServerModule;
@@ -52,4 +52,13 @@ declare global {
52
52
  */
53
53
  'changeWorld': (world: any, opt: any) => Promise<void>;
54
54
  }
55
+ interface PlayerBehaviorInputMap {
56
+ 'sendChunk': {
57
+ _input: {
58
+ x: number;
59
+ z: number;
60
+ chunk: Chunk;
61
+ };
62
+ };
63
+ }
55
64
  }
package/dist/modules.d.ts CHANGED
@@ -2,6 +2,7 @@ import { Client } from 'minecraft-protocol';
2
2
  import TypedEmitter from 'typed-emitter';
3
3
  import EventEmitter from 'events';
4
4
  import { IndexedData, Block as MinecraftDataBlock } from 'minecraft-data';
5
+ import { BehaviorEventMap } from './lib/behavior';
5
6
  declare global {
6
7
  interface PlayerEvents {
7
8
  asap: () => void;
@@ -45,7 +46,9 @@ declare global {
45
46
  interface Server extends TypedEmitter<ServerEvents> {
46
47
  mcData: IndexedData;
47
48
  }
48
- interface Player extends Omit<Entity, keyof TypedEmitter<{}>>, TypedEmitter<PlayerEvents> {
49
+ interface Player extends Omit<Entity, keyof TypedEmitter<{}>>, TypedEmitter<PlayerEvents & BehaviorEventMap<{
50
+ [K in keyof PlayerBehaviorInputMap]: PlayerBehaviorInputMap[K];
51
+ }>> {
49
52
  dimension: string | number;
50
53
  _client: Client;
51
54
  }
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.91",
4
+ "version": "0.0.92",
5
5
  "main": "dist/index.js",
6
6
  "types": "./dist/index.d.ts",
7
7
  "bin": "dist/app.js",