leafish 0.1.0__py3-none-any.whl

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.
Files changed (113) hide show
  1. leafish/__init__.py +77 -0
  2. leafish/auth/__init__.py +1 -0
  3. leafish/auth/microsoft.py +299 -0
  4. leafish/auth/offline.py +14 -0
  5. leafish/auth/session.py +48 -0
  6. leafish/bot.py +2086 -0
  7. leafish/config.py +57 -0
  8. leafish/data/__init__.py +1 -0
  9. leafish/data/registry.py +236 -0
  10. leafish/data/versions/.gitkeep +0 -0
  11. leafish/data/versions/1.21.11/attributes.json +247 -0
  12. leafish/data/versions/1.21.11/biomes.json +652 -0
  13. leafish/data/versions/1.21.11/blockCollisionShapes.json +146215 -0
  14. leafish/data/versions/1.21.11/blockLoot.json +13199 -0
  15. leafish/data/versions/1.21.11/blocks.json +44682 -0
  16. leafish/data/versions/1.21.11/commands.json +20257 -0
  17. leafish/data/versions/1.21.11/effects.json +242 -0
  18. leafish/data/versions/1.21.11/enchantments.json +980 -0
  19. leafish/data/versions/1.21.11/entities.json +4363 -0
  20. leafish/data/versions/1.21.11/entityLoot.json +1234 -0
  21. leafish/data/versions/1.21.11/foods.json +442 -0
  22. leafish/data/versions/1.21.11/items.json +10026 -0
  23. leafish/data/versions/1.21.11/language.json +7769 -0
  24. leafish/data/versions/1.21.11/loginPacket.json +19819 -0
  25. leafish/data/versions/1.21.11/mapIcons.json +212 -0
  26. leafish/data/versions/1.21.11/materials.json +233 -0
  27. leafish/data/versions/1.21.11/particles.json +462 -0
  28. leafish/data/versions/1.21.11/protocol.json +11655 -0
  29. leafish/data/versions/1.21.11/recipes.json +31864 -0
  30. leafish/data/versions/1.21.11/sounds.json +7354 -0
  31. leafish/data/versions/1.21.11/tints.json +465 -0
  32. leafish/data/versions/1.21.11/version.json +6 -0
  33. leafish/data/versions/1.21.11/windows.json +229 -0
  34. leafish/data/versions/1.21.4/attributes.json +226 -0
  35. leafish/data/versions/1.21.4/biomes.json +652 -0
  36. leafish/data/versions/1.21.4/blockCollisionShapes.json +142311 -0
  37. leafish/data/versions/1.21.4/blockLoot.json +13199 -0
  38. leafish/data/versions/1.21.4/blocks.json +41063 -0
  39. leafish/data/versions/1.21.4/commands.json +18720 -0
  40. leafish/data/versions/1.21.4/effects.json +236 -0
  41. leafish/data/versions/1.21.4/enchantments.json +959 -0
  42. leafish/data/versions/1.21.4/entities.json +4130 -0
  43. leafish/data/versions/1.21.4/entityLoot.json +1234 -0
  44. leafish/data/versions/1.21.4/foods.json +412 -0
  45. leafish/data/versions/1.21.4/items.json +9098 -0
  46. leafish/data/versions/1.21.4/language.json +7002 -0
  47. leafish/data/versions/1.21.4/loginPacket.json +18031 -0
  48. leafish/data/versions/1.21.4/mapIcons.json +212 -0
  49. leafish/data/versions/1.21.4/materials.json +134 -0
  50. leafish/data/versions/1.21.4/particles.json +450 -0
  51. leafish/data/versions/1.21.4/protocol.json +9456 -0
  52. leafish/data/versions/1.21.4/recipes.json +29693 -0
  53. leafish/data/versions/1.21.4/sounds.json +6606 -0
  54. leafish/data/versions/1.21.4/tints.json +422 -0
  55. leafish/data/versions/1.21.4/version.json +6 -0
  56. leafish/data/versions/1.21.4/windows.json +229 -0
  57. leafish/entities/__init__.py +1 -0
  58. leafish/entities/entity.py +162 -0
  59. leafish/entities/manager.py +197 -0
  60. leafish/events/__init__.py +1 -0
  61. leafish/events/emitter.py +176 -0
  62. leafish/events/events.py +63 -0
  63. leafish/exceptions.py +81 -0
  64. leafish/inventory/__init__.py +1 -0
  65. leafish/inventory/inventory.py +230 -0
  66. leafish/inventory/item.py +62 -0
  67. leafish/modules/__init__.py +1 -0
  68. leafish/modules/actions.py +625 -0
  69. leafish/modules/anvil.py +137 -0
  70. leafish/modules/chat.py +121 -0
  71. leafish/modules/client.py +269 -0
  72. leafish/modules/collector.py +86 -0
  73. leafish/modules/containers.py +268 -0
  74. leafish/modules/crafting.py +446 -0
  75. leafish/modules/creative.py +94 -0
  76. leafish/modules/farming.py +131 -0
  77. leafish/modules/fishing.py +161 -0
  78. leafish/modules/health.py +31 -0
  79. leafish/modules/movement.py +165 -0
  80. leafish/modules/pathfinder.py +257 -0
  81. leafish/modules/physics.py +265 -0
  82. leafish/modules/player.py +146 -0
  83. leafish/modules/pvp.py +192 -0
  84. leafish/modules/scoreboard.py +121 -0
  85. leafish/modules/smelting.py +163 -0
  86. leafish/modules/state.py +118 -0
  87. leafish/modules/windows.py +327 -0
  88. leafish/pathfinder/__init__.py +27 -0
  89. leafish/pathfinder/goals.py +268 -0
  90. leafish/plugins/__init__.py +177 -0
  91. leafish/protocol/__init__.py +1 -0
  92. leafish/protocol/compression.py +58 -0
  93. leafish/protocol/connection.py +210 -0
  94. leafish/protocol/encryption.py +75 -0
  95. leafish/protocol/framing.py +259 -0
  96. leafish/protocol/protodef.py +145 -0
  97. leafish/protocol/session.py +290 -0
  98. leafish/protocol/versions/__init__.py +1 -0
  99. leafish/utils/__init__.py +1 -0
  100. leafish/utils/geometry.py +173 -0
  101. leafish/utils/math.py +38 -0
  102. leafish/utils/nbt.py +477 -0
  103. leafish/utils/text.py +71 -0
  104. leafish/utils/vectors.py +145 -0
  105. leafish/version.py +86 -0
  106. leafish/world/__init__.py +1 -0
  107. leafish/world/block.py +59 -0
  108. leafish/world/chunk_codec.py +231 -0
  109. leafish/world/world.py +442 -0
  110. leafish-0.1.0.dist-info/METADATA +112 -0
  111. leafish-0.1.0.dist-info/RECORD +113 -0
  112. leafish-0.1.0.dist-info/WHEEL +4 -0
  113. leafish-0.1.0.dist-info/licenses/LICENSE +21 -0
leafish/__init__.py ADDED
@@ -0,0 +1,77 @@
1
+ """Leafish — a pure Python, asynchronous Minecraft bot framework.
2
+
3
+ Quick start::
4
+
5
+ import asyncio
6
+ from leafish import Leafish
7
+
8
+ async def main():
9
+ bot = await Leafish.create_bot(
10
+ host="localhost", username="Leafish", auth="offline",
11
+ )
12
+
13
+ @bot.on("spawn")
14
+ async def on_spawn():
15
+ print("Leafish joined the world!")
16
+
17
+ await bot.wait_until_disconnected()
18
+
19
+ asyncio.run(main())
20
+ """
21
+
22
+ from .bot import Leafish, LeafishBot
23
+ from .config import BotConfig
24
+ from .entities.entity import Entity, Mob, Player
25
+ from .events.emitter import EventEmitter
26
+ from .exceptions import (
27
+ AuthenticationError,
28
+ ConnectionError,
29
+ CraftingError,
30
+ DiggingError,
31
+ DisconnectError,
32
+ InventoryError,
33
+ LeafishError,
34
+ MovementError,
35
+ PacketDecodeError,
36
+ PacketEncodeError,
37
+ PathfindingError,
38
+ PluginError,
39
+ ProtocolError,
40
+ UnsupportedVersionError,
41
+ )
42
+ from .inventory.item import Item
43
+ from .utils.vectors import BlockPos, Vec3
44
+ from .version import list_versions
45
+ from .world.block import Block
46
+
47
+ __version__ = "0.1.0"
48
+
49
+ __all__ = [
50
+ "AuthenticationError",
51
+ "Block",
52
+ "BlockPos",
53
+ "BotConfig",
54
+ "ConnectionError",
55
+ "CraftingError",
56
+ "DiggingError",
57
+ "DisconnectError",
58
+ "Entity",
59
+ "EventEmitter",
60
+ "InventoryError",
61
+ "Item",
62
+ "Leafish",
63
+ "LeafishBot",
64
+ "LeafishError",
65
+ "Mob",
66
+ "MovementError",
67
+ "PacketDecodeError",
68
+ "PacketEncodeError",
69
+ "PathfindingError",
70
+ "Player",
71
+ "PluginError",
72
+ "ProtocolError",
73
+ "UnsupportedVersionError",
74
+ "Vec3",
75
+ "__version__",
76
+ "list_versions",
77
+ ]
@@ -0,0 +1 @@
1
+ """Leafish package."""
@@ -0,0 +1,299 @@
1
+ """Microsoft account authentication via the device-code OAuth flow.
2
+
3
+ Implements the full chain used by the official Minecraft launcher:
4
+
5
+ Microsoft OAuth2 (device code) -> Xbox Live -> XSTS -> Minecraft Services
6
+
7
+ Tokens are cached to disk so subsequent logins don't require re-auth.
8
+ No credentials or tokens are ever logged.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import asyncio
14
+ import json
15
+ import logging
16
+ import time
17
+ from collections.abc import Callable
18
+ from pathlib import Path
19
+ from typing import Any
20
+
21
+ import httpx
22
+
23
+ from ..exceptions import AuthenticationError
24
+ from .session import AuthSession
25
+
26
+ log = logging.getLogger("leafish.auth")
27
+
28
+ #: Public client ID used by Minecraft Java Edition (device-code capable).
29
+ MINECRAFT_CLIENT_ID = "00000000402b5328c11ce0d2bccecc09"
30
+ #: Alternate widely-used client id for the consumers tenant device flow.
31
+ MINECRAFT_CLIENT_ID_CONSUMERS = "00000000441cc96b"
32
+
33
+ DEVICE_CODE_URL = (
34
+ "https://login.microsoftonline.com/consumers/oauth2/v2.0/devicecode"
35
+ )
36
+ TOKEN_URL = "https://login.microsoftonline.com/consumers/oauth2/v2.0/token"
37
+ SCOPE = "XboxLive.signin offline_access"
38
+
39
+ XBL_AUTH_URL = "https://user.auth.xboxlive.com/user/authenticate"
40
+ XSTS_AUTH_URL = "https://xsts.auth.xboxlive.com/xsts/authorize"
41
+ MC_LOGIN_URL = "https://api.minecraftservices.com/authentication/login_with_xbox"
42
+ MC_PROFILE_URL = "https://api.minecraftservices.com/minecraft/profile"
43
+ MC_ENTITLEMENTS_URL = "https://api.minecraftservices.com/entitlements/mcstore"
44
+ MC_OWNERSHIP_URL = "https://api.minecraftservices.com/entitlements/license"
45
+
46
+ XBL_RP = "http://auth.xboxlive.com"
47
+ XSTS_RP = "rp://api.minecraftservices.com/"
48
+
49
+
50
+ class MicrosoftAuth:
51
+ """Authenticate a Microsoft account and obtain a Minecraft session."""
52
+
53
+ def __init__(
54
+ self,
55
+ *,
56
+ client_id: str = MINECRAFT_CLIENT_ID,
57
+ cache_path: Path | None = None,
58
+ http_client: httpx.AsyncClient | None = None,
59
+ on_device_code: Callable[[dict[str, Any]], Any] | None = None,
60
+ ) -> None:
61
+ self.client_id = client_id
62
+ self.cache_path = cache_path
63
+ self._owns_client = http_client is None
64
+ self._client = http_client or httpx.AsyncClient(timeout=30.0)
65
+ self._on_device_code = on_device_code
66
+ self._tokens: dict[str, Any] = {}
67
+ if cache_path is not None and cache_path.exists():
68
+ try:
69
+ self._tokens = json.loads(cache_path.read_text("utf-8"))
70
+ except (OSError, json.JSONDecodeError):
71
+ self._tokens = {}
72
+
73
+ async def close(self) -> None:
74
+ if self._owns_client:
75
+ await self._client.aclose()
76
+
77
+ # -- public API ---------------------------------------------------------
78
+
79
+ async def authenticate(self, username: str | None = None) -> AuthSession:
80
+ """Run the full auth flow (cached when possible)."""
81
+ msa_token = await self._msa_access_token()
82
+ xbl_token = await self._xbox_live_token(msa_token)
83
+ xsts_token = await self._xsts_token(xbl_token)
84
+ mc_token = await self._minecraft_token(xsts_token)
85
+ profile = await self._minecraft_profile(mc_token)
86
+
87
+ self._tokens["mc_access_token"] = mc_token
88
+ self._tokens["mc_token_expires"] = time.time() + 86400
89
+ self._save_cache()
90
+
91
+ name = profile.get("name", "Steve")
92
+ uuid_str = profile.get("id", "")
93
+ return AuthSession(
94
+ username=name,
95
+ uuid=_format_minecraft_uuid(uuid_str),
96
+ access_token=mc_token,
97
+ profile=profile,
98
+ )
99
+
100
+ async def refresh(self) -> AuthSession:
101
+ """Force a fresh authentication, ignoring cached tokens."""
102
+ self._tokens.pop("mc_access_token", None)
103
+ return await self.authenticate()
104
+
105
+ # -- Microsoft OAuth ------------------------------------------------------
106
+
107
+ async def _msa_access_token(self) -> str:
108
+ cached = self._tokens.get("msa_access_token")
109
+ expires = self._tokens.get("msa_expires_at", 0)
110
+ if cached and time.time() < expires - 60:
111
+ return cached
112
+ if self._tokens.get("msa_refresh_token"):
113
+ token = await self._refresh_msa_token(self._tokens["msa_refresh_token"])
114
+ if token:
115
+ return token
116
+ return await self._device_code_flow()
117
+
118
+ async def _device_code_flow(self) -> str:
119
+ """Interactive device-code login; prints the code for the user."""
120
+ try:
121
+ resp = await self._client.post(
122
+ DEVICE_CODE_URL,
123
+ data={"client_id": self.client_id, "scope": SCOPE},
124
+ headers={"Content-Type": "application/x-www-form-urlencoded"},
125
+ )
126
+ data = resp.json()
127
+ except (httpx.HTTPError, json.JSONDecodeError) as exc:
128
+ raise AuthenticationError(f"Device code request failed: {exc}") from exc
129
+ if "device_code" not in data:
130
+ raise AuthenticationError(
131
+ f"Device code flow rejected: {data.get('error_description', data)}"
132
+ )
133
+
134
+ if self._on_device_code is not None:
135
+ self._on_device_code(data)
136
+ else:
137
+ print("\n" + "=" * 60)
138
+ print("Microsoft authentication required.")
139
+ print(f"Go to: {data.get('verification_uri', data.get('verification_url'))}")
140
+ print(f"Enter code: {data.get('user_code')}")
141
+ print("=" * 60 + "\n")
142
+
143
+ interval = int(data.get("interval", 5))
144
+ deadline = time.time() + int(data.get("expires_in", 900))
145
+ device_code = data["device_code"]
146
+
147
+ while time.time() < deadline:
148
+ await asyncio.sleep(interval)
149
+ try:
150
+ resp = await self._client.post(
151
+ TOKEN_URL,
152
+ data={
153
+ "client_id": self.client_id,
154
+ "grant_type": "urn:ietf:params:oauth:grant-type:device_code",
155
+ "device_code": device_code,
156
+ },
157
+ headers={"Content-Type": "application/x-www-form-urlencoded"},
158
+ )
159
+ result = resp.json()
160
+ except (httpx.HTTPError, json.JSONDecodeError) as exc:
161
+ raise AuthenticationError(f"Token poll failed: {exc}") from exc
162
+
163
+ if "access_token" in result:
164
+ self._store_msa_tokens(result)
165
+ return result["access_token"]
166
+ error = result.get("error")
167
+ if error in ("authorization_pending", "slow_down"):
168
+ continue
169
+ raise AuthenticationError(
170
+ f"Microsoft auth failed: {result.get('error_description', error)}"
171
+ )
172
+ raise AuthenticationError("Device code flow timed out")
173
+
174
+ async def _refresh_msa_token(self, refresh_token: str) -> str | None:
175
+ try:
176
+ resp = await self._client.post(
177
+ TOKEN_URL,
178
+ data={
179
+ "client_id": self.client_id,
180
+ "grant_type": "refresh_token",
181
+ "refresh_token": refresh_token,
182
+ "scope": SCOPE,
183
+ },
184
+ headers={"Content-Type": "application/x-www-form-urlencoded"},
185
+ )
186
+ result = resp.json()
187
+ except (httpx.HTTPError, json.JSONDecodeError):
188
+ return None
189
+ if "access_token" not in result:
190
+ return None
191
+ self._store_msa_tokens(result)
192
+ return result["access_token"]
193
+
194
+ def _store_msa_tokens(self, result: dict[str, Any]) -> None:
195
+ self._tokens["msa_access_token"] = result["access_token"]
196
+ self._tokens["msa_expires_at"] = time.time() + int(result.get("expires_in", 3600))
197
+ if result.get("refresh_token"):
198
+ self._tokens["msa_refresh_token"] = result["refresh_token"]
199
+ self._save_cache()
200
+
201
+ # -- Xbox Live -------------------------------------------------------------
202
+
203
+ async def _xbox_live_token(self, msa_token: str) -> dict[str, str]:
204
+ """Returns ``{"Token": ..., "uhs": ...}``."""
205
+ try:
206
+ resp = await self._client.post(
207
+ XBL_AUTH_URL,
208
+ json={
209
+ "Properties": {
210
+ "AuthMethod": "RPS",
211
+ "SiteName": "user.auth.xboxlive.com",
212
+ "RpsTicket": f"d={msa_token}",
213
+ },
214
+ "RelyingParty": XBL_RP,
215
+ "TokenType": "JWT",
216
+ },
217
+ )
218
+ data = resp.json()
219
+ except (httpx.HTTPError, json.JSONDecodeError) as exc:
220
+ raise AuthenticationError(f"Xbox Live auth failed: {exc}") from exc
221
+ if "Token" not in data:
222
+ raise AuthenticationError(
223
+ f"Xbox Live auth failed: {data.get('XErr', data)}"
224
+ )
225
+ uhs = data.get("DisplayClaims", {}).get("xui", [{}])[0].get("uhs", "")
226
+ return {"Token": data["Token"], "uhs": uhs}
227
+
228
+ async def _xsts_token(self, xbl: dict[str, str]) -> str:
229
+ try:
230
+ resp = await self._client.post(
231
+ XSTS_AUTH_URL,
232
+ json={
233
+ "Properties": {
234
+ "SandboxId": "RETAIL",
235
+ "UserTokens": [xbl["Token"]],
236
+ },
237
+ "RelyingParty": XSTS_RP,
238
+ "TokenType": "JWT",
239
+ },
240
+ headers={"x-xbl-contract-version": "1"},
241
+ )
242
+ data = resp.json()
243
+ except (httpx.HTTPError, json.JSONDecodeError) as exc:
244
+ raise AuthenticationError(f"XSTS auth failed: {exc}") from exc
245
+ if "Token" not in data:
246
+ raise AuthenticationError(
247
+ f"XSTS auth failed: {data.get('XErr', data)}"
248
+ )
249
+ return data["Token"]
250
+
251
+ # -- Minecraft Services -----------------------------------------------------
252
+
253
+ async def _minecraft_token(self, xsts_token: str) -> str:
254
+ try:
255
+ resp = await self._client.post(
256
+ MC_LOGIN_URL,
257
+ json={"identityToken": f"XBL3.0 x={xsts_token}"},
258
+ )
259
+ data = resp.json()
260
+ except (httpx.HTTPError, json.JSONDecodeError) as exc:
261
+ raise AuthenticationError(f"Minecraft login failed: {exc}") from exc
262
+ token = data.get("access_token")
263
+ if not token:
264
+ raise AuthenticationError(
265
+ "Minecraft login failed: no access_token in response"
266
+ )
267
+ return token
268
+
269
+ async def _minecraft_profile(self, mc_token: str) -> dict[str, Any]:
270
+ headers = {"Authorization": f"Bearer {mc_token}"}
271
+ try:
272
+ resp = await self._client.get(MC_PROFILE_URL, headers=headers)
273
+ profile = resp.json()
274
+ if resp.status_code == 404 or "id" not in profile:
275
+ raise AuthenticationError(
276
+ "This Microsoft account does not own Minecraft Java Edition"
277
+ )
278
+ return profile
279
+ except httpx.HTTPError as exc:
280
+ raise AuthenticationError(f"Profile fetch failed: {exc}") from exc
281
+
282
+ # -- cache ------------------------------------------------------------------
283
+
284
+ def _save_cache(self) -> None:
285
+ if self.cache_path is None:
286
+ return
287
+ try:
288
+ self.cache_path.parent.mkdir(parents=True, exist_ok=True)
289
+ self.cache_path.write_text(json.dumps(self._tokens, indent=2), "utf-8")
290
+ except OSError as exc:
291
+ log.debug("Could not write token cache: %s", exc)
292
+
293
+
294
+ def _format_minecraft_uuid(minecraft_uuid: str) -> str:
295
+ """Minecraft profile UUIDs lack dashes; reinsert them."""
296
+ u = minecraft_uuid.replace("-", "")
297
+ if len(u) != 32:
298
+ return minecraft_uuid
299
+ return f"{u[0:8]}-{u[8:12]}-{u[12:16]}-{u[16:20]}-{u[20:32]}"
@@ -0,0 +1,14 @@
1
+ """Offline-mode authentication (no Microsoft account required)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from .session import AuthSession, offline_uuid
6
+
7
+
8
+ class OfflineAuth:
9
+ """Authentication for servers running in offline mode."""
10
+
11
+ async def authenticate(self, username: str | None = None) -> AuthSession:
12
+ if not username:
13
+ raise ValueError("offline auth requires a username")
14
+ return AuthSession(username=username, uuid=offline_uuid(username))
@@ -0,0 +1,48 @@
1
+ """Authentication session and provider abstractions."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import uuid
6
+ from dataclasses import dataclass, field
7
+ from typing import Protocol
8
+
9
+
10
+ @dataclass
11
+ class AuthSession:
12
+ """The result of a successful authentication."""
13
+
14
+ username: str
15
+ uuid: str
16
+ """Undashed or dashed UUID string accepted by ``uuid.UUID``."""
17
+
18
+ access_token: str | None = None
19
+ """Minecraft services access token (online mode only)."""
20
+
21
+ profile: dict = field(default_factory=dict)
22
+ """Extra profile data (skins, cape, etc.) when available."""
23
+
24
+ @property
25
+ def online(self) -> bool:
26
+ return self.access_token is not None
27
+
28
+
29
+ class AuthProvider(Protocol):
30
+ """Pluggable authentication provider interface."""
31
+
32
+ async def authenticate(self, username: str | None = None) -> AuthSession: ...
33
+
34
+
35
+ def offline_uuid(username: str) -> str:
36
+ """Compute the offline-mode UUID for *username*.
37
+
38
+ Minecraft derives it as ``UUID.nameUUIDFromBytes("OfflinePlayer:"+name)``
39
+ (MD5-based, version 3).
40
+ """
41
+ import hashlib
42
+
43
+ digest = hashlib.md5(f"OfflinePlayer:{username}".encode()).digest()
44
+ # Set version 3 and variant bits per RFC 4122.
45
+ b = bytearray(digest)
46
+ b[6] = (b[6] & 0x0F) | 0x30
47
+ b[8] = (b[8] & 0x3F) | 0x80
48
+ return str(uuid.UUID(bytes=bytes(b)))