fancy-twilio 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.
@@ -0,0 +1,39 @@
1
+ # GENERATED FILE — do not edit.
2
+ #
3
+ # Emitted from provider/manifest.json by weaver's generator.
4
+ # A hand-edit here is destroyed by the next protocol sync, which is worse than
5
+ # being rejected, because it works until it silently does not. Fix
6
+ # provider/manifest.json (or weaver's template/) and regenerate:
7
+ #
8
+ # npm run provider -- twilio
9
+
10
+ """Twilio for Python.
11
+
12
+ The service descriptor, its faker, its delivery contract, and one function
13
+ per operation — plain HTTP on the stdlib, no vendor SDK and no runtime
14
+ dependency.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ from ._fake import FakeValues
20
+ from .actions.message_get import message_get
21
+ from .actions.message_send import message_send
22
+ from .faker import respond
23
+ from .service import BASE_URLS, CONNECTOR_API_VERSION, REQUIRES, SANDBOX, SERVICE, TITLE, descriptor
24
+
25
+ __version__ = "0.1.0"
26
+
27
+ __all__ = [
28
+ "BASE_URLS",
29
+ "CONNECTOR_API_VERSION",
30
+ "REQUIRES",
31
+ "SANDBOX",
32
+ "SERVICE",
33
+ "TITLE",
34
+ "FakeValues",
35
+ "descriptor",
36
+ "message_get",
37
+ "message_send",
38
+ "respond",
39
+ ]
fancy_twilio/_fake.py ADDED
@@ -0,0 +1,170 @@
1
+ # GENERATED FILE — do not edit.
2
+ #
3
+ # Emitted from provider/manifest.json (via weaver's
4
+ # template/embed/py/_fake.py) by weaver's generator.
5
+ # A hand-edit here is destroyed by the next protocol sync, which is worse than
6
+ # being rejected, because it works until it silently does not. Fix
7
+ # provider/manifest.json (via weaver's template/embed/py/_fake.py) (or
8
+ # weaver's template/) and regenerate:
9
+ #
10
+ # npm run provider -- twilio
11
+
12
+ """Deterministic faker values — bit-for-bit with TypeScript and PHP.
13
+
14
+ PROVENANCE — read before editing.
15
+
16
+ This is the SINGLE SOURCE for the Python faker helpers. It exists because
17
+ ``fancy-connector-core`` has a TypeScript implementation and a PHP twin and
18
+ **no Python twin at all**, so a generated ``fancy-<provider>`` package has no
19
+ shared runtime to import. Every generated package carries a copy emitted from
20
+ this file, and ``new-provider.mjs --check`` fails CI when a copy differs.
21
+
22
+ The permanent fix is a Python ``fancy-connector-core``. When it exists, this
23
+ file becomes a re-export and every provider picks it up on the next protocol
24
+ sync.
25
+
26
+ ## Bit-for-bit identical is the whole point
27
+
28
+ Not "similar": the same FNV-1a seed and the same xorshift32 sequence, so a
29
+ golden fixture asserts the exact faked payload and ALL THREE runtimes have to
30
+ produce it. That turns the faker into a parity test rather than a convenience —
31
+ which matters, because cross-runtime drift does not fail loudly. It completes,
32
+ down one path, with no error.
33
+
34
+ Python integers are unbounded, so every 32-bit operation is masked back into
35
+ range. Dropping one of those masks does not break anything visibly; it just
36
+ makes the runtimes diverge after a few hundred calls, which is the worst
37
+ possible way for this to fail.
38
+
39
+ ## Deterministic, and obviously fake
40
+
41
+ Same inputs, same output — always. A faker returning a fresh uuid every call
42
+ cannot be asserted on, so its fixtures degrade to "it did not throw", which is
43
+ the assertion that catches nothing. And the values are obviously synthetic ON
44
+ PURPOSE — ``fake_``-prefixed ids, ``example.test`` hosts, round numbers. Nobody
45
+ should ever look at a faked result and wonder whether it moved real money.
46
+ """
47
+
48
+ from __future__ import annotations
49
+
50
+ import json
51
+ from datetime import UTC, datetime, timedelta
52
+ from typing import Any
53
+
54
+ MASK = 0xFFFFFFFF
55
+
56
+ # `FakeValues.int` is part of the cross-runtime faker API — `fake.int(min, max)`
57
+ # in TypeScript, PHP and here — so the method keeps that name. Inside the class
58
+ # body it then shadows the builtin, and every LATER annotation reading `int`
59
+ # resolves to the method instead of the type. This alias is what the annotations
60
+ # after it use.
61
+ _Int = int
62
+
63
+ #: The instant every faker counts from. A constant rather than the clock,
64
+ #: because a fixture asserting on ``created`` must not start failing tomorrow.
65
+ FAKE_EPOCH = "2026-01-01T00:00:00.000Z"
66
+
67
+ _FNV_OFFSET = 0x811C9DC5
68
+ _FNV_PRIME = 0x01000193
69
+
70
+
71
+ def _stable_json(value: Any) -> str:
72
+ """Render a value the way ``JSON.stringify`` would, with sorted object keys.
73
+
74
+ Key order must not change a seed. ``json.dumps`` preserves insertion order,
75
+ so ``{a, b}`` and ``{b, a}`` would hash differently and "same inputs, same
76
+ output" would hold only for dicts that happened to be built in the same
77
+ order — the kind of almost-true that survives review and fails in a fixture
78
+ months later.
79
+ """
80
+ if isinstance(value, dict):
81
+ parts = [
82
+ f"{json.dumps(str(key))}:{_stable_json(item)}"
83
+ for key, item in sorted(value.items(), key=lambda pair: str(pair[0]))
84
+ if item is not ...
85
+ ]
86
+ return "{" + ",".join(parts) + "}"
87
+
88
+ if isinstance(value, (list, tuple)):
89
+ return "[" + ",".join(_stable_json(item) for item in value) + "]"
90
+
91
+ # `separators` matters: JavaScript emits no spaces, and a space here would
92
+ # change every seed.
93
+ return json.dumps(value, separators=(",", ":"), ensure_ascii=False)
94
+
95
+
96
+ def seed_from(*parts: Any) -> int:
97
+ """FNV-1a over the stable rendering of the parts. Twin of ``seedFrom``."""
98
+ text = "|".join(part if isinstance(part, str) else _stable_json(part) for part in parts)
99
+
100
+ hash_ = _FNV_OFFSET
101
+ # JavaScript hashes UTF-16 code units, so a character outside the BMP
102
+ # contributes two of them. Encoding to UTF-16-LE and reading pairs is what
103
+ # keeps a provider name with an emoji in it seeding identically.
104
+ for unit in _utf16_units(text):
105
+ hash_ ^= unit
106
+ hash_ = (hash_ * _FNV_PRIME) & MASK
107
+
108
+ return hash_
109
+
110
+
111
+ def _utf16_units(text: str) -> list[int]:
112
+ raw = text.encode("utf-16-le")
113
+
114
+ return [raw[i] | (raw[i + 1] << 8) for i in range(0, len(raw), 2)]
115
+
116
+
117
+ def seed_for_call(service: str, operation: str, config: dict[str, Any] | None) -> int:
118
+ """The seed for one faked call: service, operation, and the caller's config."""
119
+ return seed_from(service, operation, config or {})
120
+
121
+
122
+ class FakeValues:
123
+ """Deterministic value helpers handed to a faker.
124
+
125
+ Small on purpose. A faker's job is to return the SHAPE the provider returns
126
+ — the field names a downstream node will reference — not to simulate the
127
+ provider's business logic.
128
+ """
129
+
130
+ def __init__(self, seed: int) -> None:
131
+ masked = seed & MASK
132
+ self._state = masked if masked != 0 else 0x9E3779B9
133
+
134
+ def _next(self) -> int:
135
+ """xorshift32, matching the JS generator step for step."""
136
+ state = self._state
137
+ state ^= (state << 13) & MASK
138
+ state &= MASK
139
+ state ^= state >> 17
140
+ state ^= (state << 5) & MASK
141
+ state &= MASK
142
+ self._state = state
143
+
144
+ return state
145
+
146
+ def hex(self, length: _Int) -> str:
147
+ """A stable lowercase hex string of ``length`` characters."""
148
+ out = ""
149
+ while len(out) < length:
150
+ out += format(self._next(), "08x")
151
+
152
+ return out[:length]
153
+
154
+ def id(self, prefix: str) -> str:
155
+ """A stable id with the provider's usual prefix: ``id("ch")`` -> ``ch_fake_1a2b3c``."""
156
+ return f"{prefix}_fake_{self.hex(12)}"
157
+
158
+ def int(self, minimum: int, maximum: int) -> int:
159
+ """A stable integer in ``[minimum, maximum]``."""
160
+ return minimum + (self._next() % max(1, maximum - minimum + 1))
161
+
162
+ def pick(self, options: list[Any]) -> Any:
163
+ """Pick a stable element of a list."""
164
+ return options[self._next() % len(options)]
165
+
166
+ def timestamp(self, offset_seconds: _Int = 0) -> str:
167
+ """A fixed ISO-8601 instant, offset by whole seconds. Never ``now()``."""
168
+ base = datetime(2026, 1, 1, tzinfo=UTC) + timedelta(seconds=offset_seconds)
169
+
170
+ return base.strftime("%Y-%m-%dT%H:%M:%S") + ".000Z"
@@ -0,0 +1,569 @@
1
+ # GENERATED FILE — do not edit.
2
+ #
3
+ # Emitted from provider/manifest.json (via weaver's
4
+ # template/embed/py/_runtime.py) by weaver's generator.
5
+ # A hand-edit here is destroyed by the next protocol sync, which is worse than
6
+ # being rejected, because it works until it silently does not. Fix
7
+ # provider/manifest.json (via weaver's template/embed/py/_runtime.py) (or
8
+ # weaver's template/) and regenerate:
9
+ #
10
+ # npm run provider -- twilio
11
+
12
+ """The minimum connector runtime, in the standard library only.
13
+
14
+ PROVENANCE — read before editing.
15
+
16
+ This is the SINGLE SOURCE for the Python connector runtime, and it is
17
+ deliberately much smaller than ``@particle-academy/fancy-connector-core``. It
18
+ exists because that package has a TypeScript implementation and a PHP twin and
19
+ **no Python twin at all**. Every generated ``fancy-<provider>`` package carries
20
+ a copy emitted from this file, and ``new-provider.mjs --check`` fails CI when a
21
+ copy differs.
22
+
23
+ The permanent fix is a Python ``fancy-connector-core``. When it exists, this
24
+ file becomes a re-export and every provider picks it up on the next protocol
25
+ sync.
26
+
27
+ ## What it does, and what it deliberately does not
28
+
29
+ It owns the WIRE: the estate, the auth placement, one call path, the faker
30
+ branch, an idempotency header, and HMAC delivery verification.
31
+
32
+ It owns NO GATE. Approval, liveness, consent, second review and every journal
33
+ belong to the host, because each is enforced in ONE place and every connector
34
+ inherits it from the dispatch path rather than implementing it.
35
+
36
+ Three properties that are asserted rather than promised:
37
+
38
+ - **Nothing here reads the environment.** Credentials are arguments. A package
39
+ that reached for ``os.environ`` would bypass the host's discipline entirely.
40
+ - **Nothing here retries an ambiguous failure.** A request that may or may not
41
+ have arrived is repeated only when the caller has said repeating it is
42
+ harmless.
43
+ - **Nothing here phones home.** No telemetry, no central service, and no URL
44
+ this module contacts that the connector did not name.
45
+
46
+ ## Zero dependencies is a constraint, not an accident
47
+
48
+ ``urllib`` for HTTP, ``hmac``/``hashlib`` for signatures. A vendor SDK is
49
+ third-party code subject to the kit's full approval bar, and one SDK per
50
+ provider is hundreds of dependencies nobody is tracking.
51
+ """
52
+
53
+ from __future__ import annotations
54
+
55
+ import hashlib
56
+ import hmac
57
+ import json
58
+ import time
59
+ import urllib.error
60
+ import urllib.parse
61
+ import urllib.request
62
+ from collections.abc import Callable
63
+ from dataclasses import dataclass, field
64
+ from typing import Any, Literal
65
+
66
+ Mode = Literal["fake", "sandbox", "live", "auto"]
67
+
68
+
69
+ class ConnectorError(Exception):
70
+ """Something went wrong talking to the provider."""
71
+
72
+ def __init__(self, message: str, *, status: int | None = None, retryable: bool = False) -> None:
73
+ super().__init__(message)
74
+ self.status = status
75
+ #: Whether repeating this exact request is known to be harmless. Defaults
76
+ #: to False: an ambiguous failure is only retryable when the caller said
77
+ #: so, not when a retry would be convenient.
78
+ self.retryable = retryable
79
+
80
+
81
+ class ConnectorConfigError(ConnectorError):
82
+ """The call was refused before anything was sent. Nothing was attempted."""
83
+
84
+
85
+ class ConnectorAuthError(ConnectorError):
86
+ """The provider rejected the credential."""
87
+
88
+
89
+ class ConnectorModeError(ConnectorError):
90
+ """The requested estate does not exist for this provider."""
91
+
92
+
93
+ @dataclass
94
+ class PreparedRequest:
95
+ """An outgoing request, after the service descriptor has authorised it."""
96
+
97
+ method: str
98
+ url: str
99
+ headers: dict[str, str] = field(default_factory=dict)
100
+ query: dict[str, str] = field(default_factory=dict)
101
+ body: bytes | None = None
102
+
103
+
104
+ @dataclass
105
+ class ServiceDescriptor:
106
+ """A provider, as one value shared by every one of its operations."""
107
+
108
+ service: str
109
+ title: str
110
+ sandbox: str
111
+ base_urls: dict[str, str]
112
+ requires: list[str]
113
+ authorize: Callable[[dict[str, str | None], PreparedRequest, str], None]
114
+ faker: Callable[[str, dict[str, Any]], Any]
115
+ idempotency_header: str | None = None
116
+
117
+
118
+ @dataclass
119
+ class CallResult:
120
+ """What one call produced, and which estate produced it."""
121
+
122
+ mode: str
123
+ connection: str | None
124
+ data: Any
125
+ status: int | None = None
126
+
127
+
128
+ @dataclass
129
+ class Verification:
130
+ """Whether an inbound delivery can be trusted, and why not when it cannot."""
131
+
132
+ ok: bool
133
+ reason: str | None = None
134
+
135
+
136
+ #: The estate kinds a ``sandbox`` mode can actually point at. Mirrors the
137
+ #: TypeScript ``sandboxIsSelectable``.
138
+ SELECTABLE_SANDBOX = ("credential", "base-url", "separate-account")
139
+
140
+
141
+ def resolve_mode(descriptor: ServiceDescriptor, requested: Mode) -> str:
142
+ """Turn ``auto`` into a real estate, and refuse one the provider does not have.
143
+
144
+ A provider with no sandbox resolving ``sandbox`` to ``live`` would be the
145
+ worst possible reading: it moves real money while the caller believes it did
146
+ not.
147
+ """
148
+ if requested == "auto":
149
+ return "fake"
150
+
151
+ if requested == "sandbox" and descriptor.sandbox not in SELECTABLE_SANDBOX:
152
+ raise ConnectorModeError(
153
+ f'{descriptor.service}: sandbox was requested but this provider\'s estate is '
154
+ f'"{descriptor.sandbox}", which cannot be selected. Use "fake" to design against '
155
+ f'a shaped response, or "live" deliberately.'
156
+ )
157
+
158
+ return requested
159
+
160
+
161
+ def call(
162
+ descriptor: ServiceDescriptor,
163
+ *,
164
+ operation: str,
165
+ method: str,
166
+ path: str,
167
+ form: dict[str, Any] | None = None,
168
+ json_body: Any | None = None,
169
+ query: dict[str, Any] | None = None,
170
+ config: dict[str, Any] | None = None,
171
+ credentials: dict[str, str | None] | None = None,
172
+ mode: Mode = "auto",
173
+ connection_id: str | None = None,
174
+ idempotency_key: str | None = None,
175
+ idempotent: bool = False,
176
+ attempts: int = 3,
177
+ timeout: float = 30.0,
178
+ transport: Callable[[PreparedRequest], tuple[int, str]] | None = None,
179
+ ) -> CallResult:
180
+ """Make one call, or fake one.
181
+
182
+ ``fake`` mode never touches the network, so a connector is runnable before an
183
+ account, a key or a provider that is up.
184
+ """
185
+ resolved = resolve_mode(descriptor, mode)
186
+ config = config or {}
187
+
188
+ if resolved == "fake":
189
+ from ._fake import FakeValues, seed_for_call
190
+
191
+ fake = FakeValues(seed_for_call(descriptor.service, operation, config))
192
+
193
+ return CallResult(
194
+ mode="fake",
195
+ connection=connection_id,
196
+ data=descriptor.faker(operation, {"config": config, "fake": fake}),
197
+ )
198
+
199
+ base = descriptor.base_urls.get(resolved)
200
+ if not base:
201
+ raise ConnectorModeError(f"{descriptor.service}: no base URL for mode \"{resolved}\".")
202
+
203
+ credentials = credentials or {}
204
+ missing = [key for key in descriptor.requires if not credentials.get(key)]
205
+ if missing:
206
+ raise ConnectorConfigError(
207
+ f"{descriptor.service}: the connection is missing {', '.join(missing)}."
208
+ )
209
+
210
+ request = PreparedRequest(method=method, url=base.rstrip("/") + path)
211
+ request.query = {k: str(v) for k, v in (query or {}).items() if v is not None}
212
+
213
+ if form is not None:
214
+ request.body = urllib.parse.urlencode(
215
+ {k: v for k, v in form.items() if v is not None}, doseq=False
216
+ ).encode()
217
+ request.headers["Content-Type"] = "application/x-www-form-urlencoded"
218
+ elif json_body is not None:
219
+ request.body = json.dumps(json_body, separators=(",", ":")).encode()
220
+ request.headers["Content-Type"] = "application/json"
221
+
222
+ if idempotency_key and descriptor.idempotency_header:
223
+ request.headers[descriptor.idempotency_header] = idempotency_key
224
+
225
+ descriptor.authorize(credentials, request, resolved)
226
+
227
+ send = transport or _urllib_transport
228
+ last: ConnectorError | None = None
229
+
230
+ for attempt in range(1, max(1, attempts) + 1):
231
+ try:
232
+ status, text = send(_with_query(request, timeout))
233
+ except OSError as error: # DNS, connection reset, timeout
234
+ # Nobody can tell whether this arrived. Repeating is safe only when
235
+ # the caller has said so or the request carries an idempotency key.
236
+ last = ConnectorError(
237
+ f"{descriptor.service}: {operation} did not complete ({error}).",
238
+ retryable=idempotent or bool(idempotency_key),
239
+ )
240
+ else:
241
+ if 200 <= status < 300:
242
+ return CallResult(
243
+ mode=resolved,
244
+ connection=connection_id,
245
+ data=json.loads(text) if text else None,
246
+ status=status,
247
+ )
248
+
249
+ last = _classify(descriptor.service, operation, status, text)
250
+
251
+ if not last.retryable or attempt == attempts:
252
+ raise last
253
+
254
+ time.sleep(min(2 ** (attempt - 1), 8))
255
+
256
+ raise last if last else ConnectorError(f"{descriptor.service}: {operation} failed.")
257
+
258
+
259
+ def _with_query(request: PreparedRequest, timeout: float) -> PreparedRequest:
260
+ if not request.query:
261
+ return request
262
+
263
+ separator = "&" if "?" in request.url else "?"
264
+ joined = PreparedRequest(
265
+ method=request.method,
266
+ url=f"{request.url}{separator}{urllib.parse.urlencode(request.query)}",
267
+ headers=dict(request.headers),
268
+ body=request.body,
269
+ )
270
+ joined.headers.setdefault("_timeout", str(timeout))
271
+
272
+ return joined
273
+
274
+
275
+ def _urllib_transport(request: PreparedRequest) -> tuple[int, str]:
276
+ timeout = float(request.headers.pop("_timeout", "30"))
277
+ raw = urllib.request.Request( # noqa: S310 — the URL comes from the descriptor
278
+ request.url,
279
+ data=request.body,
280
+ headers=request.headers,
281
+ method=request.method,
282
+ )
283
+
284
+ try:
285
+ with urllib.request.urlopen(raw, timeout=timeout) as response: # noqa: S310
286
+ return response.status, response.read().decode("utf-8", "replace")
287
+ except urllib.error.HTTPError as error:
288
+ return error.code, error.read().decode("utf-8", "replace")
289
+
290
+
291
+ def _classify(service: str, operation: str, status: int, body: str) -> ConnectorError:
292
+ """Separate "it was refused" from "nobody can tell"."""
293
+ message = f"{service}: {operation} failed with {status}. {body[:400]}"
294
+
295
+ if status in (401, 403):
296
+ return ConnectorAuthError(message, status=status)
297
+ if status == 429 or status >= 500:
298
+ # A 5xx or a rate limit is the provider saying "try again", which is a
299
+ # different fact from a 4xx saying "this request is wrong".
300
+ return ConnectorError(message, status=status, retryable=True)
301
+
302
+ return ConnectorError(message, status=status)
303
+
304
+
305
+ _ALGORITHMS = {"sha256": hashlib.sha256, "sha1": hashlib.sha1, "sha512": hashlib.sha512}
306
+
307
+
308
+ def verify_hmac(
309
+ *,
310
+ raw: str,
311
+ signature: str | list[str] | None,
312
+ secret: str | None,
313
+ payload: Callable[..., str],
314
+ algorithm: str,
315
+ encoding: str = "hex",
316
+ tolerance: int | None = None,
317
+ timestamp: str | None = None,
318
+ now: int | None = None,
319
+ secret_encoding: str = "utf8", # noqa: S107 — how the secret is SPELLED, not one
320
+ secret_prefix: str | None = None,
321
+ id: str | None = None,
322
+ timestamp_unit: str = "s",
323
+ signs_request_line: bool = False,
324
+ uri: str | None = None,
325
+ method: str | None = None,
326
+ url: str | None = None,
327
+ ) -> Verification:
328
+ """Verify one inbound delivery.
329
+
330
+ Refuses rather than accepts on every missing input. That asymmetry is the
331
+ whole safety property: an unverifiable endpoint is a stranger's button for
332
+ starting workflows in your account, and defaulting to "allow" would make
333
+ every misconfiguration into an open door that looks shut.
334
+
335
+ ``raw`` must be the body EXACTLY as received. Re-serialised JSON changes key
336
+ order and whitespace and produces a mismatch that looks precisely like a
337
+ wrong secret.
338
+
339
+ ``secret_encoding`` says how the SECRET is spelled: ``utf8`` (the default,
340
+ every provider before Svix — the key is the text's bytes) or ``base64``
341
+ (the key is the DECODED bytes; Svix's ``whsec_<base64>``, half of whose
342
+ bytes are not UTF-8). ``secret_prefix`` is stripped first, and its absence
343
+ is a refusal, never a guess.
344
+ """
345
+ if not secret:
346
+ return Verification(False, "no signing secret is configured for this connection")
347
+
348
+ # A LIST when the provider sends several — Stripe signs once per active
349
+ # secret while a secret is rolled, Svix's header "could be any number of
350
+ # signatures" — and the delivery is accepted when ANY matches. A first-only
351
+ # rule fails every delivery whose first signature came from the new secret.
352
+ offered = signature if isinstance(signature, list) else [signature]
353
+ candidates = [s for s in offered if isinstance(s, str) and s]
354
+ if not candidates:
355
+ return Verification(False, "the delivery carried no signature")
356
+
357
+ digest = _ALGORITHMS.get(algorithm)
358
+ if digest is None:
359
+ return Verification(False, f'unsupported signature algorithm "{algorithm}"')
360
+
361
+ # The key is checked BEFORE anything is signed, so a secret that cannot be
362
+ # a key is named as such rather than producing a mismatch that reads like a
363
+ # wrong secret.
364
+ key = _secret_key_bytes(secret, secret_encoding, secret_prefix)
365
+ if isinstance(key, Verification):
366
+ return key
367
+
368
+ if tolerance is not None:
369
+ if not timestamp:
370
+ return Verification(
371
+ False, "the delivery carried no timestamp, and this scheme signs one"
372
+ )
373
+ try:
374
+ sent = float(timestamp)
375
+ except (TypeError, ValueError):
376
+ return Verification(False, f'the delivery timestamp "{timestamp}" is not a number')
377
+ # Converted, never compared raw: HubSpot sends MILLISECONDS, and a
378
+ # millisecond value against a window in seconds refuses every delivery.
379
+ if timestamp_unit == "ms":
380
+ sent = sent / 1000
381
+
382
+ current = int(time.time()) if now is None else now
383
+ if abs(current - sent) > tolerance:
384
+ return Verification(
385
+ False,
386
+ f"the delivery is outside the {tolerance}s replay window "
387
+ f"({int(abs(current - sent))}s old)",
388
+ )
389
+
390
+ # A payload that signs the delivery's ID (Svix) takes it as a third argument;
391
+ # the two-argument payloads every earlier scheme wrote are called as before.
392
+ # HubSpot v3 signs the REQUEST LINE: refused by name without it, and the
393
+ # uri normalised here, once, by the scheme's rule.
394
+ if signs_request_line:
395
+ if not method or not url:
396
+ return Verification(False, "the delivery carried no request method or url")
397
+ line = {"method": method, "uri": normalise_signed_uri(url, uri) if uri else url}
398
+ signed = payload(raw, timestamp, id, line)
399
+ else:
400
+ signed = payload(raw, timestamp) if id is None else payload(raw, timestamp, id)
401
+ computed = hmac.new(key, signed.encode(), digest)
402
+ expected = computed.hexdigest() if encoding == "hex" else _b64(computed.digest())
403
+
404
+ # Constant time per candidate, so a signature cannot be discovered one
405
+ # character at a time; which candidate matched is not a secret.
406
+ if not any(hmac.compare_digest(expected, candidate) for candidate in candidates):
407
+ return Verification(False, "the signature does not match")
408
+
409
+ return Verification(True)
410
+
411
+
412
+ _HUBSPOT_V3_DECODE = {
413
+ "%3A": ":", "%2F": "/", "%3F": "?", "%40": "@", "%21": "!", "%24": "$",
414
+ "%27": "'", "%28": "(", "%29": ")", "%2A": "*", "%2C": ",", "%3B": ";",
415
+ }
416
+
417
+
418
+ def normalise_signed_uri(url: str, rule: str) -> str:
419
+ """The URI a provider signs, from the URL the request arrived on.
420
+
421
+ ``hubspot-v3``: only the QUERY portion is percent-decoded, and only for
422
+ twelve escapes (case-insensitive); never its leading ``?``; any
423
+ ``#fragment`` dropped. ``%26`` and ``%3D`` stay as sent. The twin of the
424
+ core's ``normaliseSignedUri``.
425
+ """
426
+ import re
427
+
428
+ if rule != "hubspot-v3":
429
+ raise ValueError(f"unknown signed-uri rule {rule!r}")
430
+ without_fragment = url.split("#", 1)[0]
431
+ base, sep, query = without_fragment.partition("?")
432
+ if not sep:
433
+ return without_fragment
434
+ decoded = re.sub(
435
+ r"%[0-9A-Fa-f]{2}", lambda m: _HUBSPOT_V3_DECODE.get(m.group(0).upper(), m.group(0)), query
436
+ )
437
+ return f"{base}?{decoded}"
438
+
439
+
440
+ def _secret_key_bytes(
441
+ secret: str,
442
+ secret_encoding: str = "utf8", # noqa: S107 — how the secret is SPELLED, not one
443
+ secret_prefix: str | None = None,
444
+ ) -> bytes | Verification:
445
+ """The HMAC key a scheme's secret spells, or the refusal it earns."""
446
+ import base64
447
+ import binascii
448
+ import json
449
+ import re
450
+
451
+ material = secret
452
+ if secret_prefix is not None:
453
+ if not material.startswith(secret_prefix):
454
+ return Verification(
455
+ False, f"signing secret does not start with {json.dumps(secret_prefix)}"
456
+ )
457
+ material = material[len(secret_prefix) :]
458
+
459
+ if secret_encoding == "base64": # noqa: S105 — a spelling, not a password
460
+ # Strict: a lenient decode of a KEY is a key nobody can reason about.
461
+ well_formed = re.fullmatch(r"[A-Za-z0-9+/]*={0,2}", material) is not None
462
+ if not material or len(material) % 4 != 0 or not well_formed:
463
+ return Verification(False, "signing secret is not valid base64")
464
+ try:
465
+ return base64.b64decode(material, validate=True)
466
+ except (binascii.Error, ValueError):
467
+ return Verification(False, "signing secret is not valid base64")
468
+
469
+ return material.encode()
470
+
471
+
472
+ def verify_shared_token(
473
+ *,
474
+ raw: str,
475
+ headers: dict[str, str],
476
+ secret: str | None,
477
+ placement: str,
478
+ name: str,
479
+ ) -> Verification:
480
+ """Verify a delivery by a token the provider ECHOES rather than a signature it computes.
481
+
482
+ Google Calendar sends the channel's ``token`` back in ``X-Goog-Channel-Token``
483
+ on every notification — with an EMPTY body, so there is nothing to sign.
484
+ Microsoft Graph sends ``clientState`` inside every item of the
485
+ notification's ``value`` array. Same refusal-by-default as ``verify_hmac``,
486
+ same result shape, and a constant-time comparison: a token is a secret.
487
+
488
+ ``placement`` is ``header`` (then ``name`` is the header) or ``body`` (then
489
+ ``name`` is a dotted path into the JSON body; a segment ending in ``[]``
490
+ means EVERY element of that array, all of which must match — one wrong item
491
+ refuses the whole delivery). The reasons are the connector core's exact
492
+ strings, so a host logs the same words whichever runtime answered.
493
+ """
494
+ if not secret:
495
+ return Verification(False, "no shared token configured for this trigger")
496
+
497
+ tokens: list[Any]
498
+ if placement == "header":
499
+ tokens = [next((v for k, v in headers.items() if k.lower() == name.lower()), None)]
500
+ else:
501
+ try:
502
+ parsed = json.loads(raw)
503
+ except ValueError:
504
+ return Verification(False, "delivery body is not JSON")
505
+ tokens = _read_tokens(parsed, name.split("."))
506
+
507
+ present = [t for t in tokens if t is not None and t != ""]
508
+ if not present:
509
+ return Verification(False, "delivery carried no token")
510
+
511
+ # Every element is compared, none is skipped: a batch is accepted as a whole
512
+ # or refused as a whole.
513
+ matched = len(present) == len(tokens)
514
+ for token in present:
515
+ matched = (isinstance(token, str) and hmac.compare_digest(secret, token)) and matched
516
+
517
+ return Verification(True) if matched else Verification(False, "token did not match")
518
+
519
+
520
+ def _read_tokens(value: Any, segments: list[str]) -> list[Any]:
521
+ """Every value at a dotted path; a ``[]`` segment fans out over a list. Absent is None."""
522
+ if not segments:
523
+ return [value]
524
+
525
+ head, rest = segments[0], segments[1:]
526
+ each_element = head.endswith("[]")
527
+ key = head[:-2] if each_element else head
528
+
529
+ if not isinstance(value, dict) or key not in value:
530
+ return [None]
531
+ nxt = value[key]
532
+
533
+ if not each_element:
534
+ return _read_tokens(nxt, rest)
535
+ if not isinstance(nxt, list):
536
+ return [None]
537
+
538
+ found: list[Any] = []
539
+ for element in nxt:
540
+ found.extend(_read_tokens(element, rest))
541
+
542
+ return found
543
+
544
+
545
+ def handshake_response(
546
+ param: str | None, query: dict[str, str | list[str]], content_type: str = "text/plain"
547
+ ) -> dict[str, Any] | None:
548
+ """Answer a provider's challenge — Graph POSTs ``?validationToken=…`` when a
549
+ subscription is created and refuses to create it unless the token comes
550
+ back, decoded, as ``text/plain``. The pure half: what to send, or None when
551
+ the request is not a challenge at all (no parameter, an empty one, or a
552
+ trigger that declares no handshake). ``query`` is already URL-decoded by
553
+ the framework.
554
+ """
555
+ if param is None:
556
+ return None
557
+
558
+ raw = query.get(param)
559
+ token = raw[0] if isinstance(raw, list) and raw else raw
560
+ if not token or isinstance(token, list):
561
+ return None
562
+
563
+ return {"status": 200, "contentType": content_type, "body": token}
564
+
565
+
566
+ def _b64(raw: bytes) -> str:
567
+ import base64
568
+
569
+ return base64.b64encode(raw).decode()
@@ -0,0 +1,16 @@
1
+ # GENERATED FILE — do not edit.
2
+ #
3
+ # Emitted from provider/actions/ by weaver's generator.
4
+ # A hand-edit here is destroyed by the next protocol sync, which is worse than
5
+ # being rejected, because it works until it silently does not. Fix
6
+ # provider/actions/ (or weaver's template/) and regenerate:
7
+ #
8
+ # npm run provider -- twilio
9
+
10
+ from .message_get import message_get
11
+ from .message_send import message_send
12
+
13
+ __all__ = [
14
+ "message_get",
15
+ "message_send",
16
+ ]
@@ -0,0 +1,82 @@
1
+ # GENERATED FILE — do not edit.
2
+ #
3
+ # Emitted from provider/actions/message-get.json by weaver's generator.
4
+ # A hand-edit here is destroyed by the next protocol sync, which is worse than
5
+ # being rejected, because it works until it silently does not. Fix
6
+ # provider/actions/message-get.json (or weaver's template/) and regenerate:
7
+ #
8
+ # npm run provider -- twilio
9
+
10
+ """Read a message's current status, segments, price and error code.
11
+
12
+ GET /2010-04-01/Accounts/{AccountSid}/Messages/{Sid}.json —
13
+ https://www.twilio.com/docs/messaging/api/message-resource#fetch-a-message-resource
14
+
15
+ This describes the request. `call` resolves the connection, picks the
16
+ estate, and either calls Twilio or calls the faker.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ from typing import Any
22
+ from urllib.parse import quote
23
+
24
+ from .._runtime import CallResult, ConnectorConfigError, Mode, call
25
+ from ..service import descriptor
26
+
27
+ OPERATION = "message_get"
28
+ METHOD = "GET"
29
+ PATH = "/2010-04-01/Accounts/{AccountSid}/Messages/{Sid}.json"
30
+ SIDE_EFFECTS = "none"
31
+
32
+
33
+ def body(config: dict[str, Any]) -> dict[str, Any]:
34
+ """Build the form body for one call, failing loudly and specifically."""
35
+ if config.get("sid") is None or config.get("sid") == "":
36
+ raise ConnectorConfigError(
37
+ "message_get: \"sid\" is required (Message SID)."
38
+ )
39
+
40
+ out: dict[str, Any] = {}
41
+
42
+ return out
43
+
44
+
45
+
46
+ def path(config: dict[str, Any]) -> str:
47
+ """The request path, with each config value URL-ENCODED into it.
48
+
49
+ `PATH` above is the TEMPLATE, which is what the descriptor advertises;
50
+ this is what a caller sends. A value interpolated raw changes WHICH URL is
51
+ called — a range like `Sheet1!A:B`, or a sheet named `Q1/Q2` — and the
52
+ provider answers 404 about the document rather than about the encoding.
53
+ """
54
+ return (
55
+ "/2010-04-01/Accounts/"
56
+ + "{AccountSid}"
57
+ + "/Messages/"
58
+ + quote(str(config.get("sid") or ""), safe="")
59
+ + ".json"
60
+ )
61
+
62
+ def message_get(
63
+ config: dict[str, Any],
64
+ *,
65
+ credentials: dict[str, str | None] | None = None,
66
+ mode: Mode = "auto",
67
+ connection_id: str | None = None,
68
+ attempts: int = 3,
69
+ ) -> CallResult:
70
+ """Read a message's current status, segments, price and error code."""
71
+ return call(
72
+ descriptor(),
73
+ operation=OPERATION,
74
+ method=METHOD,
75
+ path=PATH,
76
+ form=body(config),
77
+ config=config,
78
+ credentials=credentials,
79
+ mode=mode,
80
+ connection_id=connection_id,
81
+ attempts=attempts,
82
+ )
@@ -0,0 +1,112 @@
1
+ # GENERATED FILE — do not edit.
2
+ #
3
+ # Emitted from provider/actions/message-send.json by weaver's generator.
4
+ # A hand-edit here is destroyed by the next protocol sync, which is worse than
5
+ # being rejected, because it works until it silently does not. Fix
6
+ # provider/actions/message-send.json (or weaver's template/) and regenerate:
7
+ #
8
+ # npm run provider -- twilio
9
+
10
+ """Send a text message.
11
+
12
+ POST /2010-04-01/Accounts/{AccountSid}/Messages.json —
13
+ https://www.twilio.com/docs/messaging/api/message-resource#create-a-message-resource
14
+
15
+ This describes the request. `call` resolves the connection, picks the
16
+ estate, and either calls Twilio or calls the faker.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ from typing import Any
22
+
23
+ from .._runtime import CallResult, ConnectorConfigError, Mode, call
24
+ from ..service import descriptor
25
+
26
+ OPERATION = "message_send"
27
+ METHOD = "POST"
28
+ PATH = "/2010-04-01/Accounts/{AccountSid}/Messages.json"
29
+ SIDE_EFFECTS = "unsafe-to-replay"
30
+
31
+
32
+ def body(config: dict[str, Any]) -> dict[str, Any]:
33
+ """Build the form body for one call, failing loudly and specifically."""
34
+ if config.get("to") is None or config.get("to") == "":
35
+ raise ConnectorConfigError(
36
+ "message_send: \"to\" is required (To)."
37
+ )
38
+
39
+ if config.get("body") is None or config.get("body") == "":
40
+ raise ConnectorConfigError(
41
+ "message_send: \"body\" is required (Body)."
42
+ )
43
+
44
+ if not (
45
+ (config.get("from") is not None and config.get("from") != "")
46
+ or (config.get("messagingServiceSid") not in (None, ""))
47
+ ):
48
+ raise ConnectorConfigError(
49
+ "message_send: message_send needs a sender: From (a Twilio number) or a Messaging "
50
+ "Service SID. Twilio refuses a message with neither.."
51
+ )
52
+
53
+ out: dict[str, Any] = {}
54
+ _value = config.get("to")
55
+ if _value is None or _value == "":
56
+ raise ConnectorConfigError("message_send: \"to\" is required.")
57
+
58
+ out["To"] = str(_value).strip()
59
+ _value = config.get("from")
60
+ if _value is not None and _value != "":
61
+ out["From"] = str(_value)
62
+ _value = config.get("messagingServiceSid")
63
+ if _value is not None and _value != "":
64
+ out["MessagingServiceSid"] = str(_value)
65
+ _value = config.get("body")
66
+ if _value is None or _value == "":
67
+ raise ConnectorConfigError("message_send: \"body\" is required.")
68
+
69
+ out["Body"] = str(_value)
70
+ _value = config.get("statusCallback")
71
+ if _value is not None and _value != "":
72
+ out["StatusCallback"] = str(_value)
73
+
74
+ return out
75
+
76
+
77
+
78
+ def path(config: dict[str, Any]) -> str:
79
+ """The request path, with each config value URL-ENCODED into it.
80
+
81
+ `PATH` above is the TEMPLATE, which is what the descriptor advertises;
82
+ this is what a caller sends. A value interpolated raw changes WHICH URL is
83
+ called — a range like `Sheet1!A:B`, or a sheet named `Q1/Q2` — and the
84
+ provider answers 404 about the document rather than about the encoding.
85
+ """
86
+ return (
87
+ "/2010-04-01/Accounts/"
88
+ + "{AccountSid}"
89
+ + "/Messages.json"
90
+ )
91
+
92
+ def message_send(
93
+ config: dict[str, Any],
94
+ *,
95
+ credentials: dict[str, str | None] | None = None,
96
+ mode: Mode = "auto",
97
+ connection_id: str | None = None,
98
+ attempts: int = 3,
99
+ ) -> CallResult:
100
+ """Send a text message."""
101
+ return call(
102
+ descriptor(),
103
+ operation=OPERATION,
104
+ method=METHOD,
105
+ path=PATH,
106
+ form=body(config),
107
+ config=config,
108
+ credentials=credentials,
109
+ mode=mode,
110
+ connection_id=connection_id,
111
+ attempts=attempts,
112
+ )
fancy_twilio/faker.py ADDED
@@ -0,0 +1,113 @@
1
+ # GENERATED FILE — do not edit.
2
+ #
3
+ # Emitted from provider/fixtures/ by weaver's generator.
4
+ # A hand-edit here is destroyed by the next protocol sync, which is worse than
5
+ # being rejected, because it works until it silently does not. Fix
6
+ # provider/fixtures/ (or weaver's template/) and regenerate:
7
+ #
8
+ # npm run provider -- twilio
9
+
10
+ """The Twilio faker.
11
+
12
+ Bit-for-bit identical to the TypeScript and PHP fakers: the same FNV-1a seed
13
+ and the same xorshift32 sequence, so a golden fixture asserts the exact
14
+ faked payload and ALL THREE runtimes have to produce it. That turns the
15
+ faker into a parity test rather than a convenience — which matters, because
16
+ cross-runtime drift does not fail loudly. It completes, down one path, with
17
+ no error.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ from typing import Any
23
+
24
+ from ._fake import FakeValues
25
+
26
+
27
+ def _as_number(value: Any) -> float | None:
28
+ """The coercion an `"as": "integer" | "number"` config binding uses: a value
29
+ that IS a number, never int(float(...))'s uncaught ValueError on one that
30
+ merely looks like text (a text field's auto-generated example, before an
31
+ author has typed a real one).
32
+ """
33
+ try:
34
+ return float(value)
35
+ except (TypeError, ValueError):
36
+ return None
37
+
38
+
39
+ def _message_get(config: dict[str, Any], fake: FakeValues) -> Any:
40
+ return {
41
+ "sid": (
42
+ str(_v)
43
+ if (_v := config.get("sid")) is not None and _v != ""
44
+ else fake.id("SM")
45
+ ),
46
+ "account_sid": fake.id("AC"),
47
+ "status": "delivered",
48
+ "to": "+14155550100",
49
+ "from": "+14155550199",
50
+ "body": "Your code is 123456",
51
+ "num_segments": "1",
52
+ "direction": "outbound-api",
53
+ "messaging_service_sid": None,
54
+ "error_code": None,
55
+ "error_message": None,
56
+ "date_created": "Sat, 08 Nov 2026 12:00:00 +0000",
57
+ "price": "-0.00790",
58
+ "price_unit": "USD",
59
+ "api_version": "2010-04-01",
60
+ }
61
+
62
+
63
+ def _message_send(config: dict[str, Any], fake: FakeValues) -> Any:
64
+ return {
65
+ "sid": fake.id("SM"),
66
+ "account_sid": fake.id("AC"),
67
+ "status": "queued",
68
+ "to": (str(_v) if (_v := config.get("to")) is not None and _v != "" else "+14155550100"),
69
+ "from": (
70
+ str(_v)
71
+ if (_v := config.get("from")) is not None and _v != ""
72
+ else "+14155550199"
73
+ ),
74
+ "body": (
75
+ str(_v)
76
+ if (_v := config.get("body")) is not None and _v != ""
77
+ else "Your code is 123456"
78
+ ),
79
+ "num_segments": "1",
80
+ "direction": "outbound-api",
81
+ "messaging_service_sid": (
82
+ str(_v)
83
+ if (_v := config.get("messagingServiceSid")) is not None and _v != ""
84
+ else None
85
+ ),
86
+ "error_code": None,
87
+ "error_message": None,
88
+ "date_created": "Sat, 08 Nov 2026 12:00:00 +0000",
89
+ "price": None,
90
+ "price_unit": "USD",
91
+ "api_version": "2010-04-01",
92
+ }
93
+
94
+
95
+ def respond(operation: str, request: dict[str, Any]) -> Any:
96
+ """Dispatch to the fixture for one operation."""
97
+ config: dict[str, Any] = request.get("config") or {}
98
+ fake: FakeValues = request["fake"]
99
+
100
+ if operation == "message_get":
101
+ return _message_get(config, fake)
102
+
103
+ if operation == "message_send":
104
+ return _message_send(config, fake)
105
+
106
+ # A faker asked for an operation it has no shape for must SAY so. Making
107
+ # something up would produce a green run whose output silently has none of
108
+ # the fields the author is about to reference.
109
+ raise ValueError(
110
+ f'twilio: no fake response is defined for "{operation}". '
111
+ "Add a fixture under provider/fixtures/ and regenerate — a connector without a faker "
112
+ "cannot be developed against, tested, or demonstrated."
113
+ )
fancy_twilio/py.typed ADDED
File without changes
@@ -0,0 +1,89 @@
1
+ # GENERATED FILE — do not edit.
2
+ #
3
+ # Emitted from provider/manifest.json by weaver's generator.
4
+ # A hand-edit here is destroyed by the next protocol sync, which is worse than
5
+ # being rejected, because it works until it silently does not. Fix
6
+ # provider/manifest.json (or weaver's template/) and regenerate:
7
+ #
8
+ # npm run provider -- twilio
9
+
10
+ """Twilio, as one service descriptor shared by every Twilio operation.
11
+
12
+ The Python twin of the js and php packages' service modules.
13
+
14
+ ## The sandbox trap, written down where it is used
15
+
16
+ Twilio's test estate is selected by the CREDENTIALS, not the URL: a separate
17
+ test Account SID and test Auth Token (Console -> API keys & tokens), against
18
+ the same api.twilio.com. A live key on a node marked sandbox texts a real
19
+ phone and is billed. With test credentials only message_send works -- every
20
+ other resource, including message_get, answers 403 -- nothing is sent or
21
+ charged, no status callback fires, and From must be Twilio's magic
22
+ +15005550006 (+15005550004 as To returns 21610, the STOP case). Test
23
+ credentials are the test Account SID and Auth Token, not an API key.
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ from ._runtime import PreparedRequest, ServiceDescriptor
29
+ from .faker import respond
30
+
31
+ # The connector API version this package was GENERATED against. A literal,
32
+ # never imported: an imported constant lets an upgrade rewrite the very claim
33
+ # it exists to detect, after which the copy agrees with itself forever.
34
+ CONNECTOR_API_VERSION = 1
35
+
36
+ SERVICE = "twilio"
37
+ TITLE = "Twilio"
38
+ SANDBOX = "credential"
39
+ BASE_URLS = {
40
+ "live": "https://api.twilio.com",
41
+ "sandbox": "https://api.twilio.com",
42
+ }
43
+
44
+ """Credential keys a remote call cannot proceed without."""
45
+ REQUIRES = [
46
+ "accountSid",
47
+ "username",
48
+ "password",
49
+ ]
50
+
51
+
52
+ def authorize(
53
+ credentials: dict[str, str | None],
54
+ request: PreparedRequest,
55
+ mode: str,
56
+ ) -> None:
57
+ """Apply Twilio's auth scheme to an outgoing request.
58
+
59
+ HTTP basic, two parts: an API key SID and its secret (recommended), or the
60
+ Account SID and its Auth Token. Either way the ACCOUNT SID is also a path
61
+ segment of every URL (/2010-04-01/Accounts/{AccountSid}/...), which is why
62
+ it is its own credential rather than read out of the username: with an API
63
+ key the two differ.
64
+ """
65
+ from urllib.parse import quote as _quote
66
+
67
+ _segment = _quote(str(credentials.get("accountSid") or ""), safe="")
68
+ request.url = request.url.replace("{AccountSid}", _segment)
69
+ request.url = request.url.replace("%7BAccountSid%7D", _segment)
70
+
71
+ import base64
72
+
73
+ pair = f"{credentials.get('username') or ''}:{credentials.get('password') or ''}"
74
+ encoded = base64.b64encode(pair.encode()).decode()
75
+ request.headers["Authorization"] = f"Basic {encoded}"
76
+
77
+
78
+ def descriptor() -> ServiceDescriptor:
79
+ """The Twilio service, for the Python runtime."""
80
+ return ServiceDescriptor(
81
+ service=SERVICE,
82
+ title=TITLE,
83
+ sandbox=SANDBOX,
84
+ base_urls=BASE_URLS,
85
+ requires=REQUIRES,
86
+ authorize=authorize,
87
+ faker=respond,
88
+ idempotency_header=None,
89
+ )
@@ -0,0 +1,125 @@
1
+ Metadata-Version: 2.5
2
+ Name: fancy-twilio
3
+ Version: 0.1.0
4
+ Summary: Twilio for Python — the service descriptor, its faker, its webhook verification, and one function per operation. Plain HTTP; no vendor SDK.
5
+ Project-URL: Homepage, https://github.com/Fancy-Friends/twilio
6
+ Project-URL: Issues, https://github.com/Fancy-Friends/twilio/issues
7
+ Project-URL: Source, https://github.com/Fancy-Friends/twilio
8
+ Author: Particle Academy
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Keywords: api,connector,fancy-flow,messaging,particle-academy,twilio
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Topic :: Software Development :: Libraries
19
+ Classifier: Typing :: Typed
20
+ Requires-Python: >=3.11
21
+ Description-Content-Type: text/markdown
22
+
23
+ # Twilio
24
+
25
+ [![Fancified](art/fancified.svg)](https://particle.academy)
26
+
27
+ Twilio for [fancy-flow][flow] — as **four imported, versioned packages**, one
28
+ per runtime. Not vendored source: a copy cannot be upgraded, and third-party APIs
29
+ change.
30
+
31
+ [flow]: https://github.com/Particle-Academy/fancy-flow
32
+
33
+ | Runtime | Package | Install |
34
+ |---|---|---|
35
+ | Authoring surface (every host) | `@particle-academy/twilio-ui` | `npm install @particle-academy/twilio-ui` |
36
+ | Node | `@particle-academy/twilio-js` | `npm install @particle-academy/twilio-js` |
37
+ | PHP 8.4+ | `particle-academy/twilio-php` | `composer require particle-academy/twilio-php` |
38
+ | Python 3.11+ | `fancy-twilio` | `pip install fancy-twilio` |
39
+
40
+ The `ui` package is the editor surface and is React on every host — a PHP or
41
+ Python project installs it *and* its own runtime package, and never the `js` one.
42
+
43
+ ## What it costs you
44
+
45
+ One dependency: `@particle-academy/fancy-connector-core` (or
46
+ `particle-academy/fancy-connector-core` on Composer), which the `js` and `php`
47
+ packages pull in themselves. The Python package has **zero** runtime
48
+ dependencies.
49
+
50
+ **No Twilio SDK.** Plain HTTP, deliberately: a vendor SDK is third-party code
51
+ subject to the kit's full approval bar, and one per provider is hundreds of
52
+ dependencies nobody is tracking.
53
+
54
+ ## Setting it up
55
+
56
+ Everything below is generated from `provider/manifest.json`, so it cannot disagree with what the packages do.
57
+
58
+ ### Credentials
59
+
60
+ A Twilio connection holds 3 values.
61
+
62
+ Every value here is `account` scope: one per connected account, not one per installation.
63
+
64
+ | Field | Scope | Secret | Where it comes from |
65
+ |---|---|---|---|
66
+ | **Account SID** | per connected account | not secret | AC followed by 32 hex characters, from the Twilio Console. It is part of every request URL. |
67
+ | **API key SID (or Account SID)** | per connected account | not secret | An API key SID from the Twilio Console (API keys & tokens), recommended. Or the Account SID again, to authenticate with the Auth Token. |
68
+ | **API key secret (or Auth Token)** | per connected account | **secret** | The secret shown once when the API key was created, or the account's Auth Token. The Auth Token can do everything on the account; an API key can be revoked on its own. |
69
+
70
+ ### The estate
71
+
72
+ **Twilio decides live-or-test by the KEY, not by the endpoint.** The same host serves both, and a live key pointed at a node marked “sandbox” reaches the real estate and SUCCEEDS. Nothing in the request distinguishes them, which is why credentials sit on the connection rather than on each node.
73
+
74
+ > Twilio's test estate is selected by the CREDENTIALS, not the URL: a separate test Account SID and test Auth Token (Console -> API keys & tokens), against the same api.twilio.com. A live key on a node marked sandbox texts a real phone and is billed. With test credentials only message_send works -- every other resource, including message_get, answers 403 -- nothing is sent or charged, no status callback fires, and From must be Twilio's magic +15005550006 (+15005550004 as To returns 21610, the STOP case). Test credentials are the test Account SID and Auth Token, not an API key.
75
+
76
+ ## What it can do
77
+
78
+ ### Actions
79
+
80
+ #### `message_get` — Twilio message
81
+
82
+ Read a message's current status, segments, price and error code.
83
+
84
+ `GET /2010-04-01/Accounts/{AccountSid}/Messages/{Sid}.json` · reads only — safe to replay
85
+
86
+ | Input | Required | What it is |
87
+ |---|---|---|
88
+ | `sid` | yes | From message_send's data.sid. |
89
+
90
+ #### `message_send` — Send an SMS with Twilio
91
+
92
+ Send a text message.
93
+
94
+ `POST /2010-04-01/Accounts/{AccountSid}/Messages.json` · **unsafe to replay** — a retried durable run does it TWICE
95
+
96
+ | Input | Required | What it is |
97
+ |---|---|---|
98
+ | `to` | yes | The recipient in E.164, e.g. +14155550100. |
99
+ | `from` | no | A Twilio number you own, in E.164, or an alphanumeric sender ID where the destination allows one. Give this or a Messaging Service. |
100
+ | `messagingServiceSid` | no | MG... A Messaging Service picks the sender from its pool. Give this or From. |
101
+ | `body` | yes | The text. Up to 1,600 characters. A character outside GSM-7 makes the whole message UCS-2, which halves how much fits in each billed segment. |
102
+ | `statusCallback` | no | Optional. Twilio POSTs delivery status changes here. Verifying those requests arrives in 0.2.0. |
103
+
104
+ ## Run it before you have credentials
105
+
106
+ Every operation ships a **faker**, whether or not Twilio has a sandbox. Set a
107
+ node's mode to `fake` and it returns the shape Twilio actually publishes — the
108
+ same field names, deterministically — so you can wire the downstream nodes before
109
+ touching an account, a key, or a network.
110
+
111
+ ## This repository is generated
112
+
113
+ `provider/` is the source. Everything under `packages/` is emitted from it and
114
+ **must not be hand-edited** — CI regenerates and diffs on every push, and the
115
+ next protocol sync destroys anything it finds. See [`AGENTS.md`](AGENTS.md).
116
+
117
+ ## Two namespaces, which do not match on purpose
118
+
119
+ The repo is `github.com/Fancy-Friends/twilio`; the packages publish under
120
+ `particle-academy`. Nothing derives one from the other — the names come from
121
+ weaver's `friends.json` and nowhere else.
122
+
123
+ ## Licence
124
+
125
+ MIT.
@@ -0,0 +1,13 @@
1
+ fancy_twilio/__init__.py,sha256=6pcqMs9E7Yl66OHPdobkt7fn98swOkZb3ILnAtImvfs,1047
2
+ fancy_twilio/_fake.py,sha256=2BGIhSTuM9-NirJ-bCcVn6a_sdbuzERTQ410C9OeBN4,6648
3
+ fancy_twilio/_runtime.py,sha256=QOk4lEpH4mWM8RpF1a34yVwf4vPRVWezkx_lX3Kik1c,21226
4
+ fancy_twilio/faker.py,sha256=eO8iwSh-k9V2DyaUi1yht6UeNssWM4d_0MzaQSJVhVQ,3835
5
+ fancy_twilio/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ fancy_twilio/service.py,sha256=Z_oi5-lIUju_Mzxqv0Heiu-tBPc9AbaFIBxuLDOzGZg,3102
7
+ fancy_twilio/actions/__init__.py,sha256=wPHOcAWeaG0QmRsyMB73PtHt0AfuwJIee6uZGCUh2lY,460
8
+ fancy_twilio/actions/message_get.py,sha256=bF0r_vGDiXNPhGNFRMXwpMRSyWDAlh5IyTJGJ-S1nIA,2540
9
+ fancy_twilio/actions/message_send.py,sha256=FIsINF41YSvhhVT_fbqlQiQO2Vxxi1q-YW5fM6F_sDc,3614
10
+ fancy_twilio-0.1.0.dist-info/METADATA,sha256=LypUiTzkk9Ngywq01HV5oJxhkPotNgoCkTipi9VlILg,6154
11
+ fancy_twilio-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
12
+ fancy_twilio-0.1.0.dist-info/licenses/LICENSE,sha256=nBlLZPUsduZ364Sj4w82nIJyfqWKvlBnDV3j-czSMnA,1073
13
+ fancy_twilio-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Particle Academy
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.