aiveth 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.
aiveth/__init__.py ADDED
@@ -0,0 +1,29 @@
1
+ """Aiveth by Gooclaim for Python: verify tokens and webhooks, and manage your organization's
2
+ people (the admin API)."""
3
+
4
+ from .client import Aiveth
5
+ from .errors import (
6
+ AivethError,
7
+ InsufficientScopeError,
8
+ TokenVerificationError,
9
+ WebhookVerificationError,
10
+ )
11
+ from .mcp import challenge, metadata_url, protected_resource_metadata
12
+ from .tokens import Tokens, has_flag
13
+ from .webhooks import TOLERANCE_SECONDS, verify_webhook
14
+
15
+ __all__ = [
16
+ "TOLERANCE_SECONDS",
17
+ "Aiveth",
18
+ "AivethError",
19
+ "InsufficientScopeError",
20
+ "TokenVerificationError",
21
+ "Tokens",
22
+ "WebhookVerificationError",
23
+ "challenge",
24
+ "has_flag",
25
+ "metadata_url",
26
+ "protected_resource_metadata",
27
+ "verify_webhook",
28
+ ]
29
+ __version__ = "0.1.0"
aiveth/_address.py ADDED
@@ -0,0 +1,17 @@
1
+ """Aiveth's address as the SDK trusts it: https only (http just for this machine, while you
2
+ develop) — over plain http anyone on the network could hand you their own keys."""
3
+
4
+ from urllib.parse import urlsplit
5
+
6
+ from .errors import AivethError
7
+
8
+ _LOCAL = ("localhost", "127.0.0.1", "::1")
9
+
10
+
11
+ def checked(url: str, what: str = "base_url") -> str:
12
+ parts = urlsplit(url)
13
+ if parts.scheme == "https" and parts.hostname:
14
+ return url.rstrip("/")
15
+ if parts.scheme == "http" and parts.hostname in _LOCAL:
16
+ return url.rstrip("/")
17
+ raise AivethError(f"{what} must be an https:// address (http only for localhost).")
aiveth/client.py ADDED
@@ -0,0 +1,322 @@
1
+ """Aiveth's admin API for your organization's own server: ``Authorization: Bearer aiveth_sk_…``,
2
+ an API key made in the console (Developers → API keys) with the powers it needs. Every call is in
3
+ your organization's activity log as done by that key."""
4
+
5
+ from __future__ import annotations # a method named `list` must not hide the builtin
6
+
7
+ from typing import Any
8
+ from urllib.parse import quote, urlencode
9
+
10
+ import httpx
11
+
12
+ from ._address import checked
13
+ from .errors import AivethError
14
+ from .tokens import Tokens
15
+
16
+ IMPORT_AT_ONCE = 500
17
+
18
+
19
+ class _Part:
20
+ def __init__(self, aiveth: Aiveth) -> None:
21
+ self._l = aiveth
22
+
23
+
24
+ class People(_Part):
25
+ def list(self, email: str | None = None) -> list[dict[str, Any]]:
26
+ return self._l.call(
27
+ "GET", "/v1/admin/people" + (f"?{urlencode({'email': email})}" if email else "")
28
+ )
29
+
30
+ def get(self, person_id: str) -> dict[str, Any]:
31
+ return self._l.call("GET", f"/v1/admin/people/{quote(person_id, safe='')}")
32
+
33
+ def set_role(self, person_id: str, role: str) -> dict[str, Any]:
34
+ return self._l.call(
35
+ "PUT", f"/v1/admin/people/{quote(person_id, safe='')}/role", {"role": role}
36
+ )
37
+
38
+ def set_active(self, person_id: str, active: bool) -> dict[str, Any]:
39
+ return self._l.call(
40
+ "PUT", f"/v1/admin/people/{quote(person_id, safe='')}/status", {"active": active}
41
+ )
42
+
43
+ def sign_out(self, person_id: str) -> None:
44
+ self._l.call("DELETE", f"/v1/admin/people/{quote(person_id, safe='')}/sessions")
45
+
46
+ def fields(self, person_id: str) -> dict[str, Any]:
47
+ return self._l.call("GET", f"/v1/admin/people/{quote(person_id, safe='')}/fields")
48
+
49
+ def set_fields(self, person_id: str, **kinds: dict[str, Any]) -> dict[str, Any]:
50
+ """``public=…`` reaches sign-in tokens, so it also needs the key's organization:fields
51
+ power; ``private=…`` and ``person=…`` need people:manage."""
52
+ return self._l.call("PUT", f"/v1/admin/people/{quote(person_id, safe='')}/fields", kinds)
53
+
54
+ def import_people(self, people: list[dict[str, Any]]) -> dict[str, Any]:
55
+ """At most 500 a call — `import_all` splits a longer list. A person's ``password_hash``
56
+ with ``password_hasher`` bcrypt or argon2id comes straight across; anything else waits for
57
+ your old system's check at their first sign-in."""
58
+ return self._l.call("POST", "/v1/admin/people/import", {"people": people})
59
+
60
+ def import_all(self, people: list[dict[str, Any]]) -> dict[str, Any]:
61
+ total: dict[str, Any] = {
62
+ "created": 0,
63
+ "with_password": 0, # nosec B105 — a count's name
64
+ "awaiting_check": 0,
65
+ "no_password": 0, # nosec B105 — a count's name
66
+ "skipped": [],
67
+ }
68
+ for start in range(0, len(people), IMPORT_AT_ONCE):
69
+ one = self.import_people(people[start : start + IMPORT_AT_ONCE])
70
+ for key in ("created", "with_password", "awaiting_check", "no_password"):
71
+ total[key] += one.get(key, 0)
72
+ total["skipped"].extend(one.get("skipped", []))
73
+ return total
74
+
75
+ def send_reset_emails(self) -> dict[str, Any]:
76
+ """A reset link to everyone still waiting for your old system's check — once a day."""
77
+ return self._l.call("POST", "/v1/admin/people/import/reset-emails")
78
+
79
+
80
+ class Invitations(_Part):
81
+ def list(self) -> list[dict[str, Any]]:
82
+ return self._l.call("GET", "/v1/admin/invitations")
83
+
84
+ def send(self, email: str, role: str | None = None) -> dict[str, Any]:
85
+ return self._l.call(
86
+ "POST", "/v1/admin/invitations", {"email": email, **({"role": role} if role else {})}
87
+ )
88
+
89
+ def withdraw(self, invitation_id: str) -> None:
90
+ self._l.call("DELETE", f"/v1/admin/invitations/{quote(invitation_id, safe='')}")
91
+
92
+
93
+ class Roles(_Part):
94
+ def list(self) -> list[dict[str, Any]]:
95
+ return self._l.call("GET", "/v1/admin/roles")
96
+
97
+
98
+ class Organization(_Part):
99
+ def fields(self) -> dict[str, Any]:
100
+ return self._l.call("GET", "/v1/admin/organization/fields")
101
+
102
+ def set_fields(self, **kinds: dict[str, Any]) -> dict[str, Any]:
103
+ return self._l.call("PUT", "/v1/admin/organization/fields", kinds)
104
+
105
+
106
+ class Events(_Part):
107
+ def list(
108
+ self,
109
+ *,
110
+ types: list[str] | None = None,
111
+ after: str | None = None,
112
+ limit: int | None = None,
113
+ range_start: str | None = None,
114
+ ) -> dict[str, Any]:
115
+ """Oldest first; page on with ``list_metadata["after"]``."""
116
+ query = {
117
+ k: v
118
+ for k, v in {
119
+ "types": ",".join(types) if types else None,
120
+ "after": after,
121
+ "limit": limit,
122
+ "range_start": range_start,
123
+ }.items()
124
+ if v
125
+ }
126
+ return self._l.call("GET", "/v1/events" + (f"?{urlencode(query)}" if query else ""))
127
+
128
+
129
+ def _q(**params: Any) -> str:
130
+ kept = {k: v for k, v in params.items() if v not in (None, "", False)}
131
+ return f"?{urlencode(kept)}" if kept else ""
132
+
133
+
134
+ class Consents(_Part):
135
+ """DPDP consent for an app that asks on its own screen (a key with consent:read and
136
+ consent:write). The answers are the same chained records as Aiveth's own screen."""
137
+
138
+ _BASE = "/v1/admin/consents"
139
+
140
+ def record(
141
+ self, person_id: str, notice_version: int, choices: dict[str, bool],
142
+ language: str | None = None,
143
+ ) -> dict[str, Any]: # fmt: skip
144
+ """The answers your app's screen collected, to ``notice_version`` (409 when not current)."""
145
+ body: dict[str, Any] = {"person_id": person_id, "notice_version": notice_version,
146
+ "choices": choices} # fmt: skip
147
+ if language:
148
+ body["language"] = language
149
+ return self._l.call("POST", self._BASE, body)
150
+
151
+ def check(self, person_id: str, purpose: str) -> dict[str, Any]:
152
+ """Ask before using the data: ``granted`` = a yes to the current notice that holds now
153
+ (a time-bound one past ``expires_at`` is no)."""
154
+ return self._l.call("GET", f"{self._BASE}/check{_q(person_id=person_id, purpose=purpose)}")
155
+
156
+ def allows(self, person_id: str, purpose: str) -> bool:
157
+ """`check`, as a yes or no."""
158
+ return bool(self.check(person_id, purpose)["granted"])
159
+
160
+ def get(self, person_id: str) -> dict[str, Any]:
161
+ return self._l.call("GET", f"{self._BASE}/{quote(person_id, safe='')}")
162
+
163
+ def withdraw(self, person_id: str, purpose: str) -> dict[str, Any]:
164
+ """From your app's own settings page — as easy as giving it."""
165
+ return self._l.call(
166
+ "DELETE", f"{self._BASE}/{quote(person_id, safe='')}/{quote(purpose, safe='')}"
167
+ )
168
+
169
+ def receipt(self, person_id: str) -> dict[str, Any]:
170
+ """{receipt, claims}: the signed receipt (``typ`` consent-receipt+jwt — check it against
171
+ your Aiveth's JWKS) and what it says."""
172
+ return self._l.call("GET", f"{self._BASE}/{quote(person_id, safe='')}/receipt")
173
+
174
+ def import_earlier(self, notice_version: int, people: list[dict[str, Any]]) -> dict[str, Any]:
175
+ """Consent given before Aiveth, at most 500 a call — `import_all` splits a longer list.
176
+ Each: ``person_id`` or ``email``, ``choices``, ``given_at`` (ISO 8601 with its zone),
177
+ ``source`` (where, in words)."""
178
+ return self._l.call("POST", f"{self._BASE}/import",
179
+ {"notice_version": notice_version, "people": people}) # fmt: skip
180
+
181
+ def import_all(self, notice_version: int, people: list[dict[str, Any]]) -> dict[str, Any]:
182
+ total: dict[str, Any] = {"recorded": 0, "unchanged": 0, "skipped": []}
183
+ for start in range(0, len(people), IMPORT_AT_ONCE):
184
+ one = self.import_earlier(notice_version, people[start : start + IMPORT_AT_ONCE])
185
+ total["recorded"] += one.get("recorded", 0)
186
+ total["unchanged"] += one.get("unchanged", 0)
187
+ total["skipped"].extend({**s, "row": str(int(s["row"]) + start)}
188
+ for s in one.get("skipped", [])) # fmt: skip
189
+ return total
190
+
191
+
192
+ class Authorization(_Part):
193
+ """Fine-grained permissions: roles on parts of your organization. Types and roles are made in
194
+ the console; your server registers parts, gives roles on them and asks the check."""
195
+
196
+ _BASE = "/v1/admin/authorization"
197
+
198
+ def check(
199
+ self, person_id: str, permission: str, resource_type: str, resource_external_id: str
200
+ ) -> dict[str, Any]:
201
+ """``{allowed, via}`` — may this person do ``permission`` on this part? Unknown parts,
202
+ other organizations' and suspended people are always no (``authorization:read``)."""
203
+ return self._l.call("POST", f"{self._BASE}/check", {
204
+ "person_id": person_id, "permission": permission, "resource_type": resource_type,
205
+ "resource_external_id": resource_external_id}) # fmt: skip
206
+
207
+ def resources_for(
208
+ self, person_id: str, permission: str, type: str | None = None
209
+ ) -> dict[str, Any]:
210
+ """``{everywhere, resources}`` — the parts this person may do ``permission`` on."""
211
+ return self._l.call("GET", f"{self._BASE}/people/{quote(person_id, safe='')}/resources"
212
+ + _q(permission=permission, type=type)) # fmt: skip
213
+
214
+ def access_of(self, person_id: str) -> list[dict[str, Any]]:
215
+ return self._l.call("GET", f"{self._BASE}/people/{quote(person_id, safe='')}/access")
216
+
217
+ def register(self, **part: str) -> dict[str, Any]:
218
+ """``type, external_id, name, parent_type?, parent_external_id?`` (``resources:write``)."""
219
+ return self._l.call("POST", f"{self._BASE}/resources", part)
220
+
221
+ def find(self, type: str, external_id: str) -> dict[str, Any] | None:
222
+ query = _q(type=type, external_id=external_id)
223
+ found = self._l.call("GET", f"{self._BASE}/resources{query}")
224
+ return found[0] if found else None
225
+
226
+ def get(self, part_id: str) -> dict[str, Any]:
227
+ return self._l.call("GET", f"{self._BASE}/resources/{quote(part_id, safe='')}")
228
+
229
+ def people_with(self, part_id: str, permission: str) -> list[dict[str, Any]]:
230
+ return self._l.call("GET", f"{self._BASE}/resources/{quote(part_id, safe='')}/people"
231
+ + _q(permission=permission)) # fmt: skip
232
+
233
+ def change(self, part_id: str, **change: str) -> dict[str, Any]:
234
+ """``name?``, or a new parent of the same type: ``parent_type, parent_external_id``."""
235
+ return self._l.call("PATCH", f"{self._BASE}/resources/{quote(part_id, safe='')}", change)
236
+
237
+ def remove(self, part_id: str, *, everything_below: bool = False) -> None:
238
+ """Refused while parts sit under it, unless ``everything_below``."""
239
+ self._l.call("DELETE", f"{self._BASE}/resources/{quote(part_id, safe='')}"
240
+ + _q(everything_below="true" if everything_below else None)) # fmt: skip
241
+
242
+ def give(
243
+ self,
244
+ resource_type: str,
245
+ resource_external_id: str,
246
+ role: str,
247
+ *,
248
+ person_id: str | None = None,
249
+ group_id: str | None = None,
250
+ ) -> dict[str, Any]:
251
+ """A role on a part to one person or one group (``authorization:write``) — never to the
252
+ key's maker."""
253
+ holder = {"person_id": person_id} if person_id else {"group_id": group_id}
254
+ return self._l.call("POST", f"{self._BASE}/access", {
255
+ "resource_type": resource_type, "resource_external_id": resource_external_id,
256
+ "role": role, **holder}) # fmt: skip
257
+
258
+ def take(self, access_id: str) -> None:
259
+ self._l.call("DELETE", f"{self._BASE}/access/{quote(access_id, safe='')}")
260
+
261
+
262
+ class Aiveth:
263
+ """``base_url``: your Aiveth address. ``api_key``: ``aiveth_sk_…`` — only for the admin API
264
+ and events; token and webhook checks need none. ``client``: an httpx.Client (tests)."""
265
+
266
+ def __init__(
267
+ self,
268
+ base_url: str,
269
+ api_key: str | None = None,
270
+ *,
271
+ client: httpx.Client | None = None,
272
+ timeout: float = 10.0,
273
+ ) -> None:
274
+ base_url = checked(base_url)
275
+ if api_key is not None and not api_key.startswith("aiveth_sk_"):
276
+ raise AivethError("An API key starts with aiveth_sk_.")
277
+ self._base = base_url.rstrip("/")
278
+ self._key = api_key
279
+ self._client = client or httpx.Client(timeout=timeout)
280
+ self.tokens = Tokens(self._base, self._client)
281
+ self.people = People(self)
282
+ self.invitations = Invitations(self)
283
+ self.roles = Roles(self)
284
+ self.organization = Organization(self)
285
+ self.events = Events(self)
286
+ self.authorization = Authorization(self)
287
+ self.consents = Consents(self)
288
+
289
+ def call(self, method: str, path: str, body: Any = None) -> Any:
290
+ if not self._key:
291
+ raise AivethError('This needs an API key (api_key="aiveth_sk_…").')
292
+ try:
293
+ res = self._client.request(
294
+ method,
295
+ f"{self._base}{path}",
296
+ json=body,
297
+ headers={"Authorization": f"Bearer {self._key}"},
298
+ )
299
+ except httpx.HTTPError as exc:
300
+ raise AivethError(f"Couldn't reach Aiveth ({type(exc).__name__}).") from exc
301
+ if res.status_code == 204:
302
+ return None
303
+ try:
304
+ found = res.json() if res.content else None
305
+ except ValueError: # an error page that isn't JSON: its status still says what happened
306
+ found = None
307
+ if res.status_code >= 400 or (found is None and res.content):
308
+ detail = found.get("detail") if isinstance(found, dict) else None
309
+ raise AivethError(
310
+ detail if isinstance(detail, str) else f"Aiveth answered {res.status_code}.",
311
+ res.status_code,
312
+ )
313
+ return found
314
+
315
+ def close(self) -> None:
316
+ self._client.close()
317
+
318
+ def __enter__(self) -> Aiveth:
319
+ return self
320
+
321
+ def __exit__(self, *_: object) -> None:
322
+ self.close()
aiveth/errors.py ADDED
@@ -0,0 +1,23 @@
1
+ """What the SDK raises — Aiveth's own words, and the HTTP status when Aiveth answered."""
2
+
3
+
4
+ class AivethError(Exception):
5
+ def __init__(self, message: str, status: int | None = None) -> None:
6
+ super().__init__(message)
7
+ self.status = status
8
+
9
+
10
+ class WebhookVerificationError(AivethError):
11
+ """A webhook whose signature, age or shape is wrong: never act on it."""
12
+
13
+
14
+ class TokenVerificationError(AivethError):
15
+ """A token that isn't Aiveth's, has ended, or is for someone else."""
16
+
17
+
18
+ class InsufficientScopeError(TokenVerificationError):
19
+ """A good token without a permission this call needs: answer 403 with `challenge(...)`."""
20
+
21
+ def __init__(self, missing: list[str]) -> None:
22
+ super().__init__("The token lacks: " + " ".join(missing))
23
+ self.missing = missing
aiveth/mcp.py ADDED
@@ -0,0 +1,54 @@
1
+ """For an MCP server that Aiveth signs people in to (MCP authorization, 2025-11-25):
2
+
3
+ - `protected_resource_metadata`: the document your server serves at
4
+ ``/.well-known/oauth-protected-resource`` (RFC 9728) — it tells AI agents to sign in with Aiveth;
5
+ - `challenge`: the ``WWW-Authenticate`` header for a 401 (no or bad token) or a 403 (a missing
6
+ permission), so the agent knows where to go and what to ask for;
7
+ - check each request's token with ``Tokens(...).verify_mcp_token(token, resource=...)``.
8
+ """
9
+
10
+ import re
11
+ from typing import Any, Literal
12
+ from urllib.parse import urlsplit
13
+
14
+ from ._address import checked
15
+
16
+
17
+ def metadata_url(resource: str) -> str:
18
+ """Where the metadata lives for a server at ``resource`` (the path-aware address)."""
19
+ parts = urlsplit(resource)
20
+ path = parts.path.rstrip("/")
21
+ return f"{parts.scheme}://{parts.netloc}/.well-known/oauth-protected-resource{path}"
22
+
23
+
24
+ def protected_resource_metadata(*, resource: str, base_url: str, scopes: list[str],
25
+ name: str | None = None) -> dict[str, Any]: # fmt: skip
26
+ """The RFC 9728 document — ``base_url`` is your Aiveth address; ``scopes`` your permissions."""
27
+ doc: dict[str, Any] = {
28
+ "resource": resource.rstrip("/"),
29
+ "authorization_servers": [checked(base_url)],
30
+ "scopes_supported": scopes,
31
+ "bearer_methods_supported": ["header"],
32
+ }
33
+ if name:
34
+ doc["resource_name"] = name
35
+ return doc
36
+
37
+
38
+ def challenge(*, resource: str, scope: list[str] | None = None,
39
+ error: Literal["invalid_token", "insufficient_scope"] | None = None,
40
+ description: str | None = None) -> str: # fmt: skip
41
+ """The ``WWW-Authenticate`` value: 401 with ``scope`` = what to ask for; 403 with
42
+ ``error="insufficient_scope"`` and the permissions the call needs."""
43
+
44
+ def quote(value: str) -> str:
45
+ return '"' + re.sub(r'["\\\r\n]', "", value) + '"'
46
+
47
+ parts = [f"resource_metadata={quote(metadata_url(resource))}"]
48
+ if scope:
49
+ parts.append(f"scope={quote(' '.join(scope))}")
50
+ if error:
51
+ parts.append(f"error={quote(error)}")
52
+ if description:
53
+ parts.append(f"error_description={quote(description)}")
54
+ return "Bearer " + ", ".join(parts)
aiveth/py.typed ADDED
File without changes
aiveth/tokens.py ADDED
@@ -0,0 +1,161 @@
1
+ """Checking Aiveth's tokens on your own server.
2
+
3
+ - An app's ID token and a machine app's token are JWTs (RS256): checked OFFLINE against Aiveth's
4
+ published keys (fetched once and cached; fetched again for a new key id, one fetch at a time).
5
+ - An app's ACCESS token is opaque (``oka_…``): only Aiveth knows it, so `user_from_access_token`
6
+ asks ``/oauth/userinfo`` — keep its answer briefly if you call it often.
7
+
8
+ Discovery must name the address you gave as its issuer, and its keys must come over https
9
+ (OIDC Discovery §4.3): otherwise anyone who could answer for it could hand you their own keys.
10
+ """
11
+
12
+ import threading
13
+ import time
14
+ from typing import Any
15
+
16
+ import httpx
17
+ import jwt
18
+
19
+ from ._address import checked
20
+ from .errors import AivethError, InsufficientScopeError, TokenVerificationError
21
+
22
+ COOLDOWN_SECONDS = 30
23
+ KEEP_SECONDS = 600
24
+ #: Clocks differ a little: a token is accepted up to this many seconds early or late.
25
+ LEEWAY_SECONDS = 60
26
+
27
+
28
+ class Tokens:
29
+ def __init__(self, base_url: str, client: httpx.Client) -> None:
30
+ self._base = checked(base_url)
31
+ self._client = client
32
+ self._discovery: dict[str, Any] | None = None
33
+ self._keys: tuple[float, dict[str, Any]] | None = None
34
+ self._fetching = threading.Lock()
35
+
36
+ def _get(self, url: str) -> httpx.Response:
37
+ try:
38
+ return self._client.get(url)
39
+ except httpx.HTTPError as exc:
40
+ raise AivethError(f"Couldn't reach Aiveth ({type(exc).__name__}).") from exc
41
+
42
+ def discover(self) -> dict[str, Any]:
43
+ if self._discovery is None:
44
+ res = self._get(f"{self._base}/.well-known/openid-configuration")
45
+ try:
46
+ found = res.json() if res.status_code == 200 else None
47
+ except ValueError:
48
+ found = None
49
+ if not isinstance(found, dict):
50
+ raise AivethError(f"Aiveth's discovery document answered {res.status_code}.",
51
+ res.status_code) # fmt: skip
52
+ if str(found.get("issuer", "")).rstrip("/") != self._base:
53
+ raise AivethError("Aiveth's discovery names another issuer than base_url.")
54
+ for field in ("jwks_uri", "userinfo_endpoint"):
55
+ checked(str(found.get(field, "")), field)
56
+ self._discovery = found
57
+ return self._discovery
58
+
59
+ def _key_for(self, kid: str | None) -> Any:
60
+ with self._fetching: # one fetch at a time: a burst of new key ids is one request
61
+ now = time.monotonic()
62
+ held = self._keys
63
+ stale = held is None or now - held[0] > KEEP_SECONDS
64
+ missing = held is not None and kid not in held[1]
65
+ if stale or (missing and held is not None and now - held[0] > COOLDOWN_SECONDS):
66
+ res = self._get(self.discover()["jwks_uri"])
67
+ if res.status_code != 200:
68
+ raise AivethError(f"Aiveth's keys answered {res.status_code}.", res.status_code)
69
+ try:
70
+ keys = {k.get("kid"): jwt.PyJWK(k).key for k in res.json().get("keys", [])}
71
+ except (ValueError, jwt.PyJWKError) as exc:
72
+ raise AivethError("Aiveth's keys couldn't be read.") from exc
73
+ self._keys = held = (now, keys)
74
+ if held is None or kid not in held[1]:
75
+ raise TokenVerificationError("The token was signed with a key Aiveth doesn't publish.")
76
+ return held[1][kid]
77
+
78
+ def _verify(self, token: str, audience: str) -> dict[str, Any]:
79
+ found = self.discover()
80
+ try:
81
+ kid = jwt.get_unverified_header(token).get("kid")
82
+ return jwt.decode(token, self._key_for(kid), algorithms=["RS256"], audience=audience,
83
+ issuer=found["issuer"], leeway=LEEWAY_SECONDS,
84
+ options={"require": ["exp", "iat", "iss", "aud", "sub"]}) # fmt: skip
85
+ except jwt.PyJWTError as exc:
86
+ raise TokenVerificationError(str(exc)) from exc
87
+
88
+ def verify_id_token(self, token: str, *, client_id: str) -> dict[str, Any]:
89
+ """An app's ID token — for THIS app, from Aiveth, not ended."""
90
+ claims = self._verify(token, client_id)
91
+ if not isinstance(claims.get("org_id"), str):
92
+ raise TokenVerificationError("Not an ID token.")
93
+ return claims
94
+
95
+ def verify_machine_token(self, token: str, *, org_id: str) -> dict[str, Any]:
96
+ """A machine app's token, meant for your organization's services."""
97
+ claims = self._verify(token, f"urn:aiveth:org:{org_id}")
98
+ if claims.get("gty") != "client-credentials" or claims.get("org_id") != org_id:
99
+ raise TokenVerificationError("Not a machine token for this organization.")
100
+ return claims
101
+
102
+ def verify_mcp_token(self, token: str, *, resource: str,
103
+ scopes: tuple[str, ...] = ()) -> dict[str, Any]: # fmt: skip
104
+ """An AI agent's token for YOUR MCP server (``resource``: its address, as registered in
105
+ Aiveth). A token for any other server is refused — the MCP spec's audience rule.
106
+ ``scopes``: permissions this call needs; missing ones raise `InsufficientScopeError`."""
107
+ claims = self._verify(token, resource.rstrip("/"))
108
+ agent = claims.get("gty") in ("authorization_code", "id-jag") and isinstance(
109
+ claims.get("client_id"), str
110
+ )
111
+ if not agent or not isinstance(claims.get("scope"), str):
112
+ raise TokenVerificationError("Not an AI agent token.")
113
+ held = set(claims["scope"].split())
114
+ missing = [s for s in scopes if s not in held]
115
+ if missing:
116
+ raise InsufficientScopeError(missing)
117
+ return claims
118
+
119
+ def user_from_access_token(self, access_token: str) -> dict[str, Any] | None:
120
+ """Who an app's (opaque) access token stands for — None when it has ended."""
121
+ try:
122
+ res = self._client.get(self.discover()["userinfo_endpoint"],
123
+ headers={"Authorization": f"Bearer {access_token}"}) # fmt: skip
124
+ except httpx.HTTPError as exc:
125
+ raise AivethError(f"Couldn't reach Aiveth ({type(exc).__name__}).") from exc
126
+ if res.status_code == 401:
127
+ return None
128
+ if res.status_code != 200:
129
+ raise AivethError(f"Aiveth answered {res.status_code}.", res.status_code)
130
+ return dict(res.json())
131
+
132
+ def connected_token(self, *, access_token: str, connection: str, client_id: str,
133
+ client_secret: str) -> dict[str, Any]: # fmt: skip
134
+ """The Google, Microsoft or GitHub token the person connected for your organization's
135
+ apps (RFC 8693 token exchange; Aiveth's "Connected accounts"): ``{access_token,
136
+ expires_in?, scope}``. Server-side only — it needs your app's secret, and the app must
137
+ have "Connected accounts" turned on."""
138
+ form = {"grant_type": "urn:ietf:params:oauth:grant-type:token-exchange",
139
+ "subject_token": access_token,
140
+ "subject_token_type": "urn:ietf:params:oauth:token-type:access_token", # nosec B105
141
+ "requested_token_type": "urn:aiveth:params:oauth:token-type:connected-account", # nosec B105
142
+ "connection": connection, "client_id": client_id,
143
+ "client_secret": client_secret} # fmt: skip
144
+ try:
145
+ res = self._client.post(self.discover()["token_endpoint"], data=form)
146
+ except httpx.HTTPError as exc:
147
+ raise AivethError(f"Couldn't reach Aiveth ({type(exc).__name__}).") from exc
148
+ try:
149
+ body = res.json()
150
+ except ValueError:
151
+ body = {}
152
+ if res.status_code != 200 or not isinstance(body.get("access_token"), str):
153
+ why = body.get("error_description") if isinstance(body, dict) else None
154
+ raise AivethError(why or f"Aiveth answered {res.status_code}.", res.status_code)
155
+ return {k: body[k] for k in ("access_token", "expires_in", "scope") if k in body}
156
+
157
+
158
+ def has_flag(claims: dict[str, Any] | None, key: str) -> bool:
159
+ """Is this feature flag on for the person? (Aiveth's feature flags, read from the token.)"""
160
+ flags = (claims or {}).get("feature_flags")
161
+ return isinstance(flags, list) and key in flags
aiveth/webhooks.py ADDED
@@ -0,0 +1,75 @@
1
+ """Aiveth signs every webhook as Standard Webhooks does: `webhook-id`, `webhook-timestamp` and
2
+ `webhook-signature` ("v1,<base64 HMAC-SHA256 of id.timestamp.body>", several while a secret was
3
+ just changed). Check the RAW body — parsing and re-serialising changes the bytes. The sign-in check
4
+ (hook) and the old system's password check are signed the same way. A message may come twice
5
+ within the 5 minutes: keep the `webhook-id`s you have handled and skip a repeat."""
6
+
7
+ import base64
8
+ import hashlib
9
+ import hmac
10
+ import json
11
+ import time
12
+ from collections.abc import Mapping
13
+ from typing import Any
14
+
15
+ from .errors import WebhookVerificationError
16
+
17
+ TOLERANCE_SECONDS = 300
18
+ #: Aiveth's secrets are 32 random bytes; shorter is a mistake in your settings.
19
+ MOST_SHORT = 16
20
+
21
+
22
+ def _header(headers: Mapping[str, str], name: str) -> str:
23
+ value = (
24
+ headers.get(name)
25
+ or headers.get(name.title())
26
+ or next((v for k, v in headers.items() if k.lower() == name), None)
27
+ )
28
+ if not value:
29
+ raise WebhookVerificationError(f"Missing the {name} header.")
30
+ return value
31
+
32
+
33
+ def verify_webhook(
34
+ raw_body: bytes | str,
35
+ headers: Mapping[str, str],
36
+ secret: str,
37
+ *,
38
+ tolerance_seconds: int = TOLERANCE_SECONDS,
39
+ now: float | None = None,
40
+ ) -> Any:
41
+ """Raises `WebhookVerificationError` unless Aiveth signed exactly these bytes, recently;
42
+ answers the parsed message. ``secret`` is the ``whsec_…`` the console showed once."""
43
+ msg_id = _header(headers, "webhook-id")
44
+ timestamp = _header(headers, "webhook-timestamp")
45
+ signatures = _header(headers, "webhook-signature")
46
+ try:
47
+ seconds = int(timestamp)
48
+ except ValueError as exc:
49
+ raise WebhookVerificationError("The webhook-timestamp is not a number.") from exc
50
+ if abs((time.time() if now is None else now) - seconds) > tolerance_seconds:
51
+ raise WebhookVerificationError("The message is too old, or from the future.")
52
+ if not secret.startswith("whsec_"):
53
+ raise WebhookVerificationError("The secret should start with whsec_.")
54
+ try: # strict, and long enough: an empty or garbled secret must never "verify" (review)
55
+ key = base64.b64decode(secret.removeprefix("whsec_"), validate=True)
56
+ except ValueError as exc:
57
+ raise WebhookVerificationError("The secret isn't a whsec_ secret Aiveth gave.") from exc
58
+ if len(key) < MOST_SHORT:
59
+ raise WebhookVerificationError("The secret is too short to be one Aiveth gave.")
60
+ body = raw_body.encode() if isinstance(raw_body, str) else raw_body
61
+ expected = hmac.new(key, f"{msg_id}.{timestamp}.".encode() + body, hashlib.sha256).digest()
62
+ for one in signatures.split(" "):
63
+ version, _, value = one.partition(",")
64
+ try:
65
+ given = base64.b64decode(value, validate=True)
66
+ except ValueError:
67
+ continue
68
+ if version == "v1" and hmac.compare_digest(given, expected):
69
+ break
70
+ else:
71
+ raise WebhookVerificationError("The signature does not match.")
72
+ try:
73
+ return json.loads(body)
74
+ except ValueError as exc:
75
+ raise WebhookVerificationError("The body is not JSON.") from exc
@@ -0,0 +1,126 @@
1
+ Metadata-Version: 2.5
2
+ Name: aiveth
3
+ Version: 0.1.0
4
+ Summary: Aiveth by Gooclaim for Python: verify tokens and webhooks, and manage your organization's people.
5
+ Author: Gooclaim
6
+ License-Expression: Apache-2.0
7
+ License-File: LICENSE
8
+ Keywords: aiveth,auth,authentication,gooclaim,jwt,oauth,oidc,sso,webhooks
9
+ Classifier: Intended Audience :: Developers
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Topic :: Security
12
+ Classifier: Typing :: Typed
13
+ Requires-Python: >=3.10
14
+ Requires-Dist: httpx>=0.27
15
+ Requires-Dist: pyjwt[crypto]>=2.9
16
+ Provides-Extra: test
17
+ Requires-Dist: pytest>=8; extra == 'test'
18
+ Description-Content-Type: text/markdown
19
+
20
+ # aiveth
21
+
22
+ Aiveth by Gooclaim for Python (3.10 or later).
23
+
24
+ ```python
25
+ from aiveth import Aiveth, verify_webhook
26
+
27
+ aiveth = Aiveth("https://aiveth.example.com", api_key=os.environ["AIVETH_API_KEY"])
28
+
29
+ claims = aiveth.tokens.verify_id_token(id_token, client_id="your-app-client-id")
30
+ user = aiveth.tokens.user_from_access_token(access_token) # None once it has ended
31
+ machine = aiveth.tokens.verify_machine_token(token, org_id="your-organization-id")
32
+
33
+ event = verify_webhook(request.body, request.headers, os.environ["AIVETH_WEBHOOK_SECRET"])
34
+
35
+ people = aiveth.people.list()
36
+ aiveth.invitations.send("new.person@example.com")
37
+ report = aiveth.people.import_all(people_from_your_old_system)
38
+ ```
39
+
40
+ Every refusal is a `AivethError` with Aiveth's own words and `status`.
41
+
42
+ A webhook may arrive twice within its 5 minutes: keep the `webhook-id`s you've handled and skip repeats.
43
+
44
+ ## Protect an MCP server (AI agents)
45
+
46
+ Register your MCP server in the console (AI agents → MCP servers) with its address and
47
+ permissions. Then, in your server:
48
+
49
+ ```python
50
+ from aiveth import Aiveth, InsufficientScopeError, TokenVerificationError, challenge, protected_resource_metadata
51
+
52
+ MCP = "https://mcp.acme.com/mcp"
53
+ aiveth = Aiveth(base_url="https://aiveth.gooclaim.com")
54
+
55
+ # GET /.well-known/oauth-protected-resource/mcp
56
+ metadata = protected_resource_metadata(resource=MCP, base_url="https://aiveth.gooclaim.com", scopes=["files:read"])
57
+
58
+ # every MCP request
59
+ try:
60
+ who = aiveth.tokens.verify_mcp_token(bearer, resource=MCP, scopes=("files:read",))
61
+ except InsufficientScopeError:
62
+ status, header = 403, challenge(resource=MCP, scope=["files:read"], error="insufficient_scope")
63
+ except TokenVerificationError:
64
+ status, header = 401, challenge(resource=MCP, scope=["files:read"])
65
+ ```
66
+
67
+ A token is for ONE MCP server (its `aud`); it lasts 10 minutes and the agent renews it.
68
+
69
+ ## Feature flags and the person's photo
70
+
71
+ ```python
72
+ from aiveth import has_flag
73
+ user = aiveth.tokens.verify_id_token(id_token, client_id=CLIENT_ID)
74
+ if has_flag(user, "new-billing"):
75
+ ... # show the new billing page
76
+ user.get("picture") # their photo's address on Aiveth (with the `profile` scope)
77
+ ```
78
+
79
+ ## A person's Google, Microsoft or GitHub token (connected accounts)
80
+
81
+ Turn on "Connected accounts" for the app in Aiveth, and let the person connect the account
82
+ (Account → Connected for apps). Then, on your server:
83
+
84
+ ```python
85
+ google = aiveth.tokens.connected_token(access_token=access_token, connection="google",
86
+ client_id=CLIENT_ID, client_secret=CLIENT_SECRET)
87
+ google["access_token"] # call Google as the person
88
+ ```
89
+
90
+ ## Roles on parts of your organization (fine-grained permissions)
91
+
92
+ Make the types of part (like `region` → `branch`) and the roles for them in the console (Parts &
93
+ access). Then your server registers each part as it makes it, gives roles on parts, and asks:
94
+
95
+ ```python
96
+ aiveth.authorization.register(type="branch", external_id="mumbai", name="Mumbai",
97
+ parent_type="region", parent_external_id="west")
98
+ aiveth.authorization.give("branch", "mumbai", "branch_approver", person_id=ravi)
99
+ answer = aiveth.authorization.check(ravi, "claim:approve", "branch", "mumbai")
100
+ answer["allowed"], answer["via"]
101
+ ```
102
+
103
+ A role on a part covers everything under it. The key needs `authorization:read` for the check,
104
+ `resources:write` to register parts and `authorization:write` to give roles.
105
+
106
+ ## Consent (India's DPDP Act) from your app's own screens
107
+
108
+ Publish your consent notice in the console (Privacy). If your app asks on its own screen instead of
109
+ Aiveth's, record the answers, check before you use the data, and let people withdraw:
110
+
111
+ ```python
112
+ aiveth.consents.record(person_id, notice_version, {"service": True, "news": False})
113
+ if aiveth.consents.allows(person_id, "news"):
114
+ send_newsletter()
115
+ aiveth.consents.withdraw(person_id, "news")
116
+ receipt = aiveth.consents.receipt(person_id)["receipt"] # signed, checkable with your JWKS
117
+ aiveth.consents.import_all(notice_version, earlier_consents) # given before Aiveth
118
+ ```
119
+
120
+ A yes with a time limit stops counting on its day, so always ask `allows` rather than keeping
121
+ the answer. The key needs `consent:read` to check and `consent:write` to record.
122
+
123
+ ## Development and production
124
+
125
+ Each environment has its own keys: `aiveth_sk_test_…` and apps `okc_test_…` for your Development
126
+ environment, `aiveth_sk_live_…` and `okc_live_…` for production.
@@ -0,0 +1,12 @@
1
+ aiveth/__init__.py,sha256=_lFu-4LqWq4X-RKLsLQQw4QVsNRmEQ42OWYzQRfAMrA,749
2
+ aiveth/_address.py,sha256=s3zJwqXneZyJ1izhqwlroq-dA64Xi3wYKP2obHg-K5c,632
3
+ aiveth/client.py,sha256=fiqvs3mEeLPxG9o1dGQ1OLEtVmlUC8F0UncCLGNXDf4,14074
4
+ aiveth/errors.py,sha256=sGrylEliMTdn9k42aNR1-CEpNKAwXgBwL4P7NuKVCls,804
5
+ aiveth/mcp.py,sha256=qabLaX2346am1sU68ErqFQO8WMe4L9PEDWbo0rxbXR0,2252
6
+ aiveth/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ aiveth/tokens.py,sha256=sAWkIqzKijzhAeU6t-YoQsTptPMJUq9D6W5DK_TejI8,8305
8
+ aiveth/webhooks.py,sha256=D31tPkX_DwiqXXxxlYxRyN81viiJQUcQgC8YKQV5t9o,3168
9
+ aiveth-0.1.0.dist-info/METADATA,sha256=igKoi83Qnuyi-vtiGOFPCvnWV3pOD11ldR8ExnQjF1A,5067
10
+ aiveth-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
11
+ aiveth-0.1.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
12
+ aiveth-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,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.