fromscratch-pystack 0.5.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 (43) hide show
  1. fromscratch_pystack-0.5.0.dist-info/METADATA +510 -0
  2. fromscratch_pystack-0.5.0.dist-info/RECORD +43 -0
  3. fromscratch_pystack-0.5.0.dist-info/WHEEL +4 -0
  4. fromscratch_pystack-0.5.0.dist-info/entry_points.txt +3 -0
  5. fromscratch_pystack-0.5.0.dist-info/licenses/LICENSE +21 -0
  6. pystack/__init__.py +1 -0
  7. pystack/_version.py +24 -0
  8. pystack/adapters/__init__.py +1 -0
  9. pystack/adapters/db_storage.py +157 -0
  10. pystack/adapters/os_pebble.py +118 -0
  11. pystack/adapters/pebble_db.py +85 -0
  12. pystack/cli.py +127 -0
  13. pystack/environment.py +272 -0
  14. pystack/plugins/__init__.py +1 -0
  15. pystack/plugins/_dbcrash_child.py +56 -0
  16. pystack/plugins/_schedagents.py +37 -0
  17. pystack/plugins/_schedalerts.py +103 -0
  18. pystack/plugins/_schedweb.py +79 -0
  19. pystack/plugins/_shared.py +26 -0
  20. pystack/plugins/_webdemo.py +171 -0
  21. pystack/plugins/base.py +201 -0
  22. pystack/plugins/coldb_plugin.py +165 -0
  23. pystack/plugins/crypto_plugin.py +115 -0
  24. pystack/plugins/docdb_plugin.py +172 -0
  25. pystack/plugins/git_plugin.py +94 -0
  26. pystack/plugins/graphdb_plugin.py +206 -0
  27. pystack/plugins/kv_plugin.py +156 -0
  28. pystack/plugins/llm_plugin.py +102 -0
  29. pystack/plugins/mq_plugin.py +290 -0
  30. pystack/plugins/net_plugin.py +247 -0
  31. pystack/plugins/pydb_plugin.py +111 -0
  32. pystack/plugins/registry.py +150 -0
  33. pystack/plugins/sched_plugin.py +235 -0
  34. pystack/plugins/search_plugin.py +151 -0
  35. pystack/plugins/tsdb_plugin.py +175 -0
  36. pystack/plugins/vecdb_plugin.py +168 -0
  37. pystack/plugins/web_plugin.py +95 -0
  38. pystack/py.typed +0 -0
  39. pystack/web/__init__.py +1 -0
  40. pystack/web/app.py +138 -0
  41. pystack/web/static/app.js +105 -0
  42. pystack/web/static/style.css +158 -0
  43. pystack/web/templates/index.html +59 -0
@@ -0,0 +1,171 @@
1
+ """The ``webdemo`` tour of PyWeb's async server.
2
+
3
+ A restaurant with a doorman: anyone may read the menu in the window, but
4
+ to get a table you show your wristband -- and the doorman hands one out
5
+ when you give the right name and password.
6
+
7
+ The demo starts a real server on a free port, then visits it with a tiny
8
+ hand-written HTTP client so every step can be seen.
9
+ """
10
+
11
+ from collections.abc import AsyncIterator
12
+ from contextlib import asynccontextmanager
13
+
14
+ from pynet.loop import run
15
+ from pynet.streams import StreamReader, open_connection
16
+ from pyweb.app import App
17
+ from pyweb.aserver import AsyncServer
18
+ from pyweb.auth import InMemoryUsers, SessionAuth, authenticate, current_user, require
19
+ from pyweb.messages import HttpRequest, HttpResponse, html, json
20
+ from pyweb.security import LoginThrottle, SessionSigner
21
+ from pyweb.sse import EventStream, ServerEvent
22
+
23
+ LOOPBACK = "127.0.0.1"
24
+ ROUNDS = 1_000 # fast for a demo; the real default is 100 000
25
+ TICKS = 3
26
+ HTTP_OK = 200
27
+ HTTP_UNAUTHORIZED = 401
28
+ _SHOWN = ("HttpOnly", "SameSite=Lax")
29
+ DEMO_NAME = "ada"
30
+ DEMO_PHRASE = "demo-password-not-real" # obviously fake
31
+ DEMO_KEY = "demo-secret-not-real-0123456789abcdef" # obviously fake
32
+
33
+
34
+ def _build_app() -> App:
35
+ """Build a fresh demo app: a public page, a login, a private API and a clock."""
36
+ users = InMemoryUsers()
37
+ users.add(DEMO_NAME, DEMO_PHRASE, rounds=ROUNDS)
38
+ auth = SessionAuth(SessionSigner(DEMO_KEY), users)
39
+ throttle = LoginThrottle()
40
+ app = App()
41
+ app.middleware(auth)
42
+
43
+ def home(_request: HttpRequest) -> HttpResponse:
44
+ """Serve the public page."""
45
+ return html("<h1>Welcome to the PyWeb demo</h1>")
46
+
47
+ def login(request: HttpRequest) -> HttpResponse:
48
+ """Hand out a session cookie for the right name and password."""
49
+ form = request.form()
50
+ user = authenticate(users, throttle, form.get("name") or "", form.get("password") or "")
51
+ if user is None:
52
+ return json({"error": "bad login"}, HTTP_UNAUTHORIZED)
53
+ response = json({"hello": user.name})
54
+ auth.login(response, user)
55
+ return response
56
+
57
+ def me(request: HttpRequest) -> dict[str, str]:
58
+ """Say who is logged in."""
59
+ user = current_user(request)
60
+ return {"user": user.name if user else ""}
61
+
62
+ def ticks(_request: HttpRequest) -> EventStream:
63
+ """Broadcast three numbered events, then stop."""
64
+
65
+ async def source() -> AsyncIterator[ServerEvent]:
66
+ """Yield tick 1 to tick 3."""
67
+ for number in range(1, TICKS + 1):
68
+ yield ServerEvent(f"tick {number}")
69
+
70
+ return EventStream(source())
71
+
72
+ app.get("/")(home)
73
+ app.post("/login", blocking=True)(login)
74
+ app.get("/api/me")(require()(me))
75
+ app.get("/ticks")(ticks)
76
+ return app
77
+
78
+
79
+ async def _read_head(reader: StreamReader) -> tuple[int, dict[str, str]]:
80
+ """Read the status line and headers; return the status and lower-cased headers."""
81
+ head = (await reader.read_until(b"\r\n\r\n")).decode().split("\r\n")
82
+ status = int(head[0].split()[1])
83
+ headers: dict[str, str] = {}
84
+ for line in head[1:]:
85
+ if ": " in line:
86
+ name, value = line.split(": ", 1)
87
+ headers[name.lower()] = value
88
+ return status, headers
89
+
90
+
91
+ @asynccontextmanager
92
+ async def _send(
93
+ port: int, request_line: str, extra_headers: str = "", body: str = ""
94
+ ) -> AsyncIterator[tuple[StreamReader, int, dict[str, str]]]:
95
+ """Send one raw HTTP request and give the reader positioned at the body.
96
+
97
+ The connection is hung up when the ``async with`` block ends, even if
98
+ reading the reply fails.
99
+ """
100
+ reader, writer = await open_connection(LOOPBACK, port)
101
+ try:
102
+ head = f"{request_line}\r\nHost: demo\r\nConnection: close\r\n{extra_headers}\r\n"
103
+ writer.write((head + body).encode())
104
+ await writer.drain()
105
+ status, headers = await _read_head(reader)
106
+ yield reader, status, headers
107
+ finally:
108
+ writer.close()
109
+ await writer.wait_closed()
110
+
111
+
112
+ async def _get(port: int, path: str, cookie: str | None = None) -> tuple[int, str]:
113
+ """GET a path (with an optional cookie) and return the status and body text."""
114
+ extra = f"Cookie: {cookie}\r\n" if cookie else ""
115
+ async with _send(port, f"GET {path} HTTP/1.1", extra) as (reader, status, headers):
116
+ length = int(headers.get("content-length", "0"))
117
+ body = await reader.read_exactly(length) if length else b""
118
+ return status, body.decode()
119
+
120
+
121
+ async def _login(port: int) -> tuple[int, str]:
122
+ """POST the demo login form and return the status and the Set-Cookie header."""
123
+ form = f"name={DEMO_NAME}&password={DEMO_PHRASE}"
124
+ extra = f"Content-Type: application/x-www-form-urlencoded\r\nContent-Length: {len(form)}\r\n"
125
+ async with _send(port, "POST /login HTTP/1.1", extra, form) as (reader, status, headers):
126
+ await reader.read_exactly(int(headers.get("content-length", "0")))
127
+ return status, headers.get("set-cookie", "")
128
+
129
+
130
+ async def _chunk(reader: StreamReader) -> str:
131
+ """Read one chunk of a chunked reply and return its text."""
132
+ size = int((await reader.read_until(b"\r\n"))[:-2], 16)
133
+ return (await reader.read_exactly(size + 2))[:-2].decode()
134
+
135
+
136
+ async def _ticks(port: int) -> tuple[int, list[str]]:
137
+ """Listen to the event stream and return the status and the three events."""
138
+ async with _send(port, "GET /ticks HTTP/1.1") as (reader, status, _headers):
139
+ events = [(await _chunk(reader)).strip().removeprefix("data: ") for _ in range(TICKS)]
140
+ return status, events
141
+
142
+
143
+ async def _tour() -> list[str]:
144
+ """Start the server, visit every route and return the printed lines."""
145
+ lines: list[str] = []
146
+ async with AsyncServer(_build_app(), access_log=False) as server:
147
+ port = server.port
148
+ status, _ = await _get(port, "/")
149
+ lines.append(f"GET / -> {status} (public page)")
150
+ status, _ = await _get(port, "/api/me")
151
+ lines.append(f"GET /api/me -> {status} (no wristband yet)")
152
+ status, set_cookie = await _login(port)
153
+ lines.append(f"POST /login -> {status}")
154
+ token, _, attributes = set_cookie.partition(";")
155
+ name = token.partition("=")[0]
156
+ flags = "; ".join(p.strip() for p in attributes.split(";") if p.strip() in _SHOWN)
157
+ lines.append(f"Set-Cookie: {name}=… ({flags})")
158
+ status, body = await _get(port, "/api/me", cookie=token)
159
+ lines.append(f"GET /api/me -> {status} {body} (wristband shown)")
160
+ status, events = await _ticks(port)
161
+ lines.append(f"GET /ticks -> {status} (event stream)")
162
+ lines.extend(f"event: {event}" for event in events)
163
+ return lines
164
+
165
+
166
+ def webdemo() -> str:
167
+ """Run the tour and return the story as text, or an error message."""
168
+ try:
169
+ return "\n".join(run(_tour()))
170
+ except Exception as exc: # noqa: BLE001
171
+ return f"error: {exc}"
@@ -0,0 +1,201 @@
1
+ """Plugin base class and protocol for PyStack extensions.
2
+
3
+ A plugin is a component that can hook into PyStack's three layers:
4
+ the PyOS shell (commands), the Pebble VM (stdlib modules), and the
5
+ web UI (Flask routes). Each hook is optional -- implement only what
6
+ your plugin needs.
7
+
8
+ Think of plugins like expansion packs for a board game. The base
9
+ game (PyStack) works on its own, but each expansion adds new pieces.
10
+ """
11
+
12
+ import functools
13
+ from collections.abc import Callable
14
+ from dataclasses import dataclass
15
+ from pathlib import Path
16
+
17
+ from pebble import StdlibModule
18
+ from pebble import Value as PebbleValue
19
+
20
+ # Type alias for a Pebble handler function (takes args, returns a value).
21
+ type PebbleHandler = Callable[[list[PebbleValue]], PebbleValue]
22
+
23
+
24
+ def pebble_handler(fn: PebbleHandler) -> PebbleHandler:
25
+ """Wrap a Pebble handler so exceptions become ``"error: ..."`` strings.
26
+
27
+ Every Pebble stdlib function needs to catch errors and return a
28
+ friendly message instead of crashing the VM. This decorator does
29
+ that automatically -- like a safety net under a trapeze artist.
30
+
31
+ Usage::
32
+
33
+ @pebble_handler
34
+ def _my_func(args: list[PebbleValue]) -> PebbleValue:
35
+ return do_something(args[0])
36
+
37
+ If ``do_something`` raises, the caller gets ``"error: <message>"``
38
+ instead of an unhandled exception.
39
+ """
40
+
41
+ @functools.wraps(fn)
42
+ def _wrapper(args: list[PebbleValue]) -> PebbleValue:
43
+ try:
44
+ return fn(args)
45
+ except Exception as exc: # noqa: BLE001
46
+ return f"error: {exc}"
47
+
48
+ return _wrapper
49
+
50
+
51
+ def pebble_method[P](
52
+ fn: Callable[[P, list[PebbleValue]], PebbleValue],
53
+ ) -> Callable[[P, list[PebbleValue]], PebbleValue]:
54
+ """Like :func:`pebble_handler`, for a Pebble function that is a plugin method.
55
+
56
+ Plugins keep their data on ``self``, so their Pebble functions are
57
+ methods. Errors still become ``"error: ..."`` strings.
58
+ """
59
+
60
+ @functools.wraps(fn)
61
+ def _wrapper(self: P, args: list[PebbleValue]) -> PebbleValue:
62
+ try:
63
+ return fn(self, args)
64
+ except Exception as exc: # noqa: BLE001
65
+ return f"error: {exc}"
66
+
67
+ return _wrapper
68
+
69
+
70
+ type ShellHandler = Callable[[list[str]], str]
71
+
72
+
73
+ def shell_handler(fn: ShellHandler) -> ShellHandler:
74
+ """Wrap a shell command so exceptions become ``"error: ..."`` messages.
75
+
76
+ The shell's twin of :func:`pebble_handler`. A typo like
77
+ ``vec insert a xyz`` should print a friendly error and give you your
78
+ prompt back -- not knock the whole shell over. The registry wraps every
79
+ plugin command with this automatically, so plugin authors can't forget.
80
+ """
81
+
82
+ @functools.wraps(fn)
83
+ def _wrapper(args: list[str]) -> str:
84
+ try:
85
+ return fn(args)
86
+ except Exception as exc: # noqa: BLE001
87
+ return f"error: {exc}"
88
+
89
+ return _wrapper
90
+
91
+
92
+ @dataclass
93
+ class ShellCommand:
94
+ """A command to register in the PyOS shell.
95
+
96
+ Args:
97
+ name: The command name (e.g., "httpd").
98
+ handler: A callable taking ``list[str]`` args and returning ``str``.
99
+ help_text: One-line description for help output.
100
+
101
+ """
102
+
103
+ name: str
104
+ handler: ShellHandler
105
+ help_text: str = ""
106
+
107
+
108
+ @dataclass
109
+ class PluginInfo:
110
+ """Metadata about a plugin.
111
+
112
+ Args:
113
+ name: Human-readable name (e.g., "PyWeb").
114
+ description: One-line summary.
115
+ version: Semantic version string.
116
+
117
+ """
118
+
119
+ name: str
120
+ description: str = ""
121
+ version: str = "0.1.0"
122
+
123
+
124
+ class Plugin:
125
+ """Base class for PyStack plugins.
126
+
127
+ Subclass this and override the hooks you need. The plugin registry
128
+ calls each hook during boot to wire your plugin into the platform.
129
+
130
+ """
131
+
132
+ def info(self) -> PluginInfo:
133
+ """Return metadata about this plugin.
134
+
135
+ Returns:
136
+ A PluginInfo with name, description, and version.
137
+
138
+ """
139
+ return PluginInfo(name=type(self).__name__)
140
+
141
+ def shell_commands(self) -> list[ShellCommand]:
142
+ """Return shell commands to register in PyOS.
143
+
144
+ Returns:
145
+ A list of ShellCommand objects (empty by default).
146
+
147
+ """
148
+ return []
149
+
150
+ def pebble_stdlib(self) -> StdlibModule | None:
151
+ """Return a Pebble stdlib module to register.
152
+
153
+ Returns:
154
+ A StdlibModule, or None if this plugin has no Pebble bindings.
155
+
156
+ """
157
+ return None
158
+
159
+ def pebble_module_name(self) -> str:
160
+ """Return the name for the Pebble stdlib module.
161
+
162
+ Only called if ``pebble_stdlib()`` returns a module.
163
+
164
+ Returns:
165
+ The import name (e.g., "web" for ``import "web"``).
166
+
167
+ """
168
+ return self.info().name.lower()
169
+
170
+ def on_boot(self) -> None:
171
+ """Run custom initialization after the plugin is registered.
172
+
173
+ Override this for setup that needs the full environment running.
174
+ """
175
+
176
+ def load_state(self, folder: Path) -> None:
177
+ """Load this plugin's saved data, before :meth:`on_boot` runs.
178
+
179
+ Like opening your saved game: if there's a save in *folder*, pick up
180
+ where you left off. The folder may not exist yet (first run), in which
181
+ case there is nothing to load.
182
+
183
+ Args:
184
+ folder: This plugin's own data folder,
185
+ ``<data dir>/<pebble module name>/``.
186
+
187
+ """
188
+
189
+ def save_state(self, folder: Path) -> None:
190
+ """Save this plugin's data so it's there next time.
191
+
192
+ Create *folder* only if there is something to write.
193
+
194
+ Args:
195
+ folder: This plugin's own data folder (same as for
196
+ :meth:`load_state`).
197
+
198
+ """
199
+
200
+ def on_shutdown(self) -> None:
201
+ """Run custom clean-up when PyStack stops (after saving)."""
@@ -0,0 +1,165 @@
1
+ """PyColDB integration plugin for PyStack.
2
+
3
+ Bridge PyColDB's column-family store into Pebble so kids can set, get,
4
+ and delete columns from their Pebble programs.
5
+
6
+ A column-family store is like a spreadsheet where every row can have
7
+ different column headers -- each row stores only the columns it needs.
8
+
9
+ Pebble module name: ``coldb``
10
+
11
+ Example Pebble usage::
12
+
13
+ import "coldb"
14
+ col_set("grades", "alice", "math", "A+")
15
+ let grade = col_get("grades", "alice", "math")
16
+ print(grade)
17
+ """
18
+
19
+ from pathlib import Path
20
+
21
+ from pebble import StdlibModule
22
+ from pebble import Value as PebbleValue
23
+ from pycoldb.column import Column
24
+ from pycoldb.keyspace import Keyspace
25
+ from pycoldb.persistence import load_keyspace, save_keyspace
26
+
27
+ from pystack.plugins.base import Plugin, PluginInfo, ShellCommand, pebble_method
28
+
29
+ _KEYSPACE_FILE = "keyspace.json"
30
+
31
+
32
+ class ColDBPlugin(Plugin):
33
+ """Integrate PyColDB column-family store functions into PyStack.
34
+
35
+ Register set/get/delete functions in Pebble's ``coldb`` stdlib
36
+ module and shell commands for interactive use.
37
+ """
38
+
39
+ def __init__(self) -> None:
40
+ """Start with no data; it is created on first use or loaded at start-up."""
41
+ self._keyspace: Keyspace | None = None
42
+
43
+ def _get_keyspace(self) -> Keyspace:
44
+ """Return this plugin's Keyspace, creating it on first use."""
45
+ if self._keyspace is None:
46
+ self._keyspace = Keyspace(name="default")
47
+ return self._keyspace
48
+
49
+ def _ensure_cf(self, name: str) -> None:
50
+ """Ensure a column family exists, creating it if needed."""
51
+ ks = self._get_keyspace()
52
+ if name not in ks.column_families:
53
+ ks.create_column_family(name)
54
+
55
+ @pebble_method
56
+ def col_set(self, args: list[PebbleValue]) -> PebbleValue:
57
+ """Set a column value in a column family."""
58
+ family = str(args[0])
59
+ row_key = str(args[1])
60
+ col_name = str(args[2])
61
+ value = str(args[3])
62
+ self._ensure_cf(family)
63
+ ks = self._get_keyspace()
64
+ ks.put(family, row_key, Column(name=col_name, value=value))
65
+ return "ok"
66
+
67
+ @pebble_method
68
+ def col_get(self, args: list[PebbleValue]) -> PebbleValue:
69
+ """Get a column value from a column family."""
70
+ family = str(args[0])
71
+ row_key = str(args[1])
72
+ col_name = str(args[2])
73
+ ks = self._get_keyspace()
74
+ try:
75
+ column = ks.get_column(family, row_key, col_name)
76
+ return str(column.value)
77
+ except Exception: # noqa: BLE001
78
+ return "not found"
79
+
80
+ @pebble_method
81
+ def col_delete(self, args: list[PebbleValue]) -> PebbleValue:
82
+ """Delete a column from a column family."""
83
+ family = str(args[0])
84
+ row_key = str(args[1])
85
+ col_name = str(args[2])
86
+ ks = self._get_keyspace()
87
+ try:
88
+ cf = ks.get_column_family(family)
89
+ cf.delete_column(row_key, col_name)
90
+ return "ok"
91
+ except Exception: # noqa: BLE001
92
+ return "not found"
93
+
94
+ def load_state(self, folder: Path) -> None:
95
+ """Load the saved keyspace, if there is one."""
96
+ path = folder / _KEYSPACE_FILE
97
+ if path.exists():
98
+ self._keyspace = load_keyspace(path)
99
+
100
+ def save_state(self, folder: Path) -> None:
101
+ """Save the keyspace, if this run used or loaded one."""
102
+ if self._keyspace is None:
103
+ return
104
+ folder.mkdir(parents=True, exist_ok=True)
105
+ save_keyspace(self._keyspace, folder / _KEYSPACE_FILE)
106
+
107
+ def info(self) -> PluginInfo:
108
+ """Return plugin metadata."""
109
+ return PluginInfo(
110
+ name="PyColDB",
111
+ description="Column-family store for Pebble programs",
112
+ version="0.1.0",
113
+ )
114
+
115
+ def pebble_module_name(self) -> str:
116
+ """Return the Pebble import name."""
117
+ return "coldb"
118
+
119
+ def pebble_stdlib(self) -> StdlibModule:
120
+ """Return the coldb stdlib module with set/get/delete functions."""
121
+ return StdlibModule(
122
+ functions={
123
+ "col_set": (4, self.col_set),
124
+ "col_get": (3, self.col_get),
125
+ "col_delete": (3, self.col_delete),
126
+ },
127
+ constants={},
128
+ )
129
+
130
+ def shell_commands(self) -> list[ShellCommand]:
131
+ """Return the col shell commands."""
132
+
133
+ def _col_cmd(args: list[str]) -> str:
134
+ """Handle col subcommands: set, get."""
135
+ if not args:
136
+ return "Usage: col <set|get> <family> <row> <col> [value]"
137
+
138
+ sub = args[0]
139
+ min_set_args = 5
140
+ min_get_args = 4
141
+
142
+ if sub == "set" and len(args) >= min_set_args:
143
+ family = args[1]
144
+ row_key = args[2]
145
+ col_name = args[3]
146
+ value = " ".join(args[4:])
147
+ self._ensure_cf(family)
148
+ self._get_keyspace().put(family, row_key, Column(name=col_name, value=value))
149
+ return f"Set {family}/{row_key}/{col_name} = '{value}'"
150
+
151
+ if sub == "get" and len(args) >= min_get_args:
152
+ family = args[1]
153
+ row_key = args[2]
154
+ col_name = args[3]
155
+ try:
156
+ column = self._get_keyspace().get_column(family, row_key, col_name)
157
+ return str(column.value)
158
+ except Exception: # noqa: BLE001
159
+ return "Not found"
160
+
161
+ return "Usage: col <set|get> <family> <row> <col> [value]"
162
+
163
+ return [
164
+ ShellCommand(name="col", handler=_col_cmd, help_text="Column-family store operations"),
165
+ ]
@@ -0,0 +1,115 @@
1
+ """PyCrypt integration plugin for PyStack.
2
+
3
+ Bridge PyCrypt's cryptographic primitives into Pebble so kids can hash
4
+ text, encrypt with Caesar ciphers, and sign messages with HMAC -- all
5
+ from their Pebble programs.
6
+
7
+ Cryptography is like a set of secret codes and tamper-proof wax seals --
8
+ it scrambles a message so only the right person can read it, and proves
9
+ nobody changed it along the way.
10
+
11
+ Pebble module name: ``crypto``
12
+
13
+ Example Pebble usage::
14
+
15
+ import "crypto"
16
+ let h = hash("hello")
17
+ print(h)
18
+
19
+ let encrypted = caesar_encrypt("SECRET", 3)
20
+ print(encrypted)
21
+ """
22
+
23
+ from pebble import StdlibModule
24
+ from pebble import Value as PebbleValue
25
+ from pycrypt.caesar import decrypt as caesar_dec
26
+ from pycrypt.caesar import encrypt as caesar_enc
27
+ from pycrypt.hashing import sha256
28
+ from pycrypt.hmac import hmac_sign as _hmac_sign
29
+ from pycrypt.hmac import hmac_verify as _hmac_verify
30
+
31
+ from pystack.plugins.base import Plugin, PluginInfo, ShellCommand, pebble_handler
32
+
33
+
34
+ @pebble_handler
35
+ def _hash(args: list[PebbleValue]) -> PebbleValue:
36
+ """Return the SHA-256 hash of a text string."""
37
+ return sha256(str(args[0]))
38
+
39
+
40
+ @pebble_handler
41
+ def _caesar_encrypt(args: list[PebbleValue]) -> PebbleValue:
42
+ """Encrypt text using the Caesar cipher with the given shift."""
43
+ text = str(args[0])
44
+ shift = int(args[1]) # type: ignore[arg-type]
45
+ return caesar_enc(text, shift)
46
+
47
+
48
+ @pebble_handler
49
+ def _caesar_decrypt(args: list[PebbleValue]) -> PebbleValue:
50
+ """Decrypt text using the Caesar cipher with the given shift."""
51
+ text = str(args[0])
52
+ shift = int(args[1]) # type: ignore[arg-type]
53
+ return caesar_dec(text, shift)
54
+
55
+
56
+ @pebble_handler
57
+ def _hmac_sign_handler(args: list[PebbleValue]) -> PebbleValue:
58
+ """Create an HMAC-SHA256 tag for a message with a secret key."""
59
+ message = str(args[0])
60
+ key = str(args[1])
61
+ return _hmac_sign(message, key)
62
+
63
+
64
+ @pebble_handler
65
+ def _hmac_verify_handler(args: list[PebbleValue]) -> PebbleValue:
66
+ """Verify that a message matches its HMAC tag."""
67
+ message = str(args[0])
68
+ tag = str(args[1])
69
+ key = str(args[2])
70
+ return _hmac_verify(message, tag, key)
71
+
72
+
73
+ class CryptoPlugin(Plugin):
74
+ """Integrate PyCrypt cryptographic functions into PyStack.
75
+
76
+ Register hashing, Caesar cipher, and HMAC functions in Pebble's
77
+ ``crypto`` stdlib module, and a ``hash`` shell command.
78
+ """
79
+
80
+ def info(self) -> PluginInfo:
81
+ """Return plugin metadata."""
82
+ return PluginInfo(
83
+ name="PyCrypt",
84
+ description="Cryptographic primitives for Pebble programs",
85
+ version="0.1.0",
86
+ )
87
+
88
+ def pebble_module_name(self) -> str:
89
+ """Return the Pebble import name."""
90
+ return "crypto"
91
+
92
+ def pebble_stdlib(self) -> StdlibModule:
93
+ """Return the crypto stdlib module with hash, Caesar, and HMAC functions."""
94
+ return StdlibModule(
95
+ functions={
96
+ "hash": (1, _hash),
97
+ "caesar_encrypt": (2, _caesar_encrypt),
98
+ "caesar_decrypt": (2, _caesar_decrypt),
99
+ "hmac_sign": (2, _hmac_sign_handler),
100
+ "hmac_verify": (3, _hmac_verify_handler),
101
+ },
102
+ constants={},
103
+ )
104
+
105
+ def shell_commands(self) -> list[ShellCommand]:
106
+ """Return the hash shell command."""
107
+
108
+ def _hash_cmd(args: list[str]) -> str:
109
+ """Print the SHA-256 hash of the given text."""
110
+ if not args:
111
+ return "Usage: hash <text>"
112
+ text = " ".join(args)
113
+ return sha256(text)
114
+
115
+ return [ShellCommand(name="hash", handler=_hash_cmd, help_text="Print SHA-256 hash")]