toolframe-auth 0.2.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 @@
1
+ """Access Password authentication provider."""
@@ -0,0 +1,34 @@
1
+ """Salted scrypt verification and separately keyed secret identification."""
2
+
3
+ import hashlib
4
+ import hmac
5
+ import secrets
6
+
7
+ SCRYPT_N = 2**17
8
+ SCRYPT_R = 8
9
+ SCRYPT_P = 1
10
+
11
+
12
+ def lookup(key, secret):
13
+ return hmac.new(key, secret.encode(), hashlib.sha256).hexdigest()
14
+
15
+
16
+ def verifier(secret, salt):
17
+ return hashlib.scrypt(
18
+ secret.encode(),
19
+ salt=bytes.fromhex(salt),
20
+ n=SCRYPT_N,
21
+ r=SCRYPT_R,
22
+ p=SCRYPT_P,
23
+ maxmem=256 * 1024 * 1024,
24
+ dklen=32,
25
+ ).hex()
26
+
27
+
28
+ def new_verifier(secret):
29
+ salt = secrets.token_hex(16)
30
+ return salt, verifier(secret, salt)
31
+
32
+
33
+ def session_digest(token):
34
+ return hashlib.sha256(token.encode()).hexdigest()
@@ -0,0 +1,355 @@
1
+ """Local identities, browser sessions and revocable delegation authority."""
2
+
3
+ import json
4
+ import math
5
+ import secrets
6
+ import time
7
+ import uuid
8
+
9
+ from toolframe_sdk import PluginError, Principal
10
+
11
+ from .crypto import session_digest
12
+
13
+ SCHEMA = """
14
+ CREATE TABLE users (
15
+ id TEXT PRIMARY KEY, label TEXT NOT NULL, scopes TEXT NOT NULL,
16
+ created_at REAL NOT NULL, expires_at REAL, disabled INTEGER NOT NULL DEFAULT 0
17
+ );
18
+ CREATE TABLE external_identities (
19
+ issuer TEXT NOT NULL, subject TEXT NOT NULL, user_id TEXT NOT NULL REFERENCES users(id),
20
+ PRIMARY KEY(issuer,subject)
21
+ );
22
+ CREATE TABLE user_sessions (
23
+ digest TEXT PRIMARY KEY, user_id TEXT NOT NULL REFERENCES users(id),
24
+ created_at REAL NOT NULL, absolute_expires REAL NOT NULL, last_activity REAL NOT NULL,
25
+ invalidated INTEGER NOT NULL DEFAULT 0
26
+ );
27
+ CREATE INDEX user_sessions_user ON user_sessions(user_id);
28
+ CREATE TABLE agent_grants (
29
+ id TEXT PRIMARY KEY, user_id TEXT NOT NULL REFERENCES users(id),
30
+ issuer TEXT NOT NULL, client_id TEXT NOT NULL, client_name TEXT NOT NULL,
31
+ resource TEXT NOT NULL, scopes TEXT NOT NULL, created_at REAL NOT NULL,
32
+ expires_at REAL NOT NULL, revoked_at REAL
33
+ );
34
+ CREATE INDEX agent_grants_user ON agent_grants(user_id);
35
+ """
36
+
37
+ METHODS = (
38
+ "federated_login",
39
+ "users",
40
+ "user_update",
41
+ "grant_create",
42
+ "grant_check",
43
+ "grants",
44
+ "revoke_grant",
45
+ )
46
+
47
+
48
+ def public(record):
49
+ return {**record, "scopes": json.loads(record["scopes"])}
50
+
51
+
52
+ def text(value, maximum=2048):
53
+ return (
54
+ isinstance(value, str)
55
+ and 0 < len(value) <= maximum
56
+ and not any(ord(char) < 32 or 0xD800 <= ord(char) <= 0xDFFF for char in value)
57
+ )
58
+
59
+
60
+ class IdentityAuthority:
61
+ def __init__(self, authority):
62
+ self.auth = authority
63
+ self.context = authority.context
64
+ self.store = authority.store
65
+
66
+ def trusted_provider(self):
67
+ if self.context.call_info.get("owner") != self.context.config.get(
68
+ "identity_provider", "oidc-auth"
69
+ ):
70
+ raise PluginError(
71
+ "forbidden",
72
+ "Only the configured identity provider may authenticate users",
73
+ )
74
+
75
+ def actor(self):
76
+ value = self.context.call_info.get("principal")
77
+ if not value:
78
+ raise PluginError(
79
+ "authentication_required", "Sign in to manage your account"
80
+ )
81
+ return Principal.model_validate(value)
82
+
83
+ def administrator(self):
84
+ actor = self.actor()
85
+ if not actor.unrestricted and "system.auth.users" not in actor.scopes:
86
+ raise PluginError("forbidden", "User administration permission required")
87
+ return actor
88
+
89
+ async def user(self, identifier, store=None):
90
+ if not text(identifier, 128):
91
+ raise PluginError("invalid_credentials", "User is unavailable")
92
+ rows = await (store or self.store).query(
93
+ "SELECT * FROM users WHERE id=?", [identifier]
94
+ )
95
+ if not rows:
96
+ raise PluginError("invalid_credentials", "User is unavailable")
97
+ return rows[0]
98
+
99
+ def active(self, user):
100
+ if user["disabled"] or (
101
+ user["expires_at"] is not None and user["expires_at"] <= time.time()
102
+ ):
103
+ raise PluginError("invalid_credentials", "User is unavailable")
104
+
105
+ def principal(self, user):
106
+ self.active(user)
107
+ return Principal(
108
+ kind="user",
109
+ credential_id=user["id"],
110
+ user_id=user["id"],
111
+ scopes=tuple(
112
+ sorted(set(json.loads(user["scopes"])) | {"system.auth.self"})
113
+ ),
114
+ expires_at=user["expires_at"],
115
+ )
116
+
117
+ def scopes(self, values, *, business=False):
118
+ catalog = self.context.call_info.get("scope_catalog", {})
119
+ if not isinstance(values, list) or not all(
120
+ isinstance(s, str)
121
+ and s in catalog
122
+ and (not business or catalog[s].get("category") == "business")
123
+ for s in values
124
+ ):
125
+ raise PluginError("invalid_request", "Supply declared permissions")
126
+ return sorted(set(values))
127
+
128
+ async def login(self, params):
129
+ self.trusted_provider()
130
+ issuer, subject = params.get("issuer"), params.get("subject")
131
+ if not text(issuer) or not text(subject, 255):
132
+ raise PluginError("invalid_credentials", "Invalid external identity")
133
+ async with self.store.transaction() as store:
134
+ links = await store.query(
135
+ "SELECT user_id FROM external_identities WHERE issuer=? AND subject=?",
136
+ [issuer, subject],
137
+ )
138
+ if links:
139
+ user = await self.user(links[0]["user_id"], store)
140
+ else:
141
+ admission = next(
142
+ (
143
+ rule
144
+ for rule in self.context.config.get("federated_identities", [])
145
+ if rule["issuer"] == issuer and rule["subject"] == subject
146
+ ),
147
+ None,
148
+ )
149
+ if admission is None:
150
+ raise PluginError(
151
+ "forbidden",
152
+ "This identity has not been admitted by an administrator",
153
+ )
154
+ scopes = self.scopes(admission["scopes"])
155
+ identifier = uuid.uuid4().hex
156
+ await store.execute(
157
+ "INSERT INTO users(id,label,scopes,created_at) VALUES(?,?,?,?)",
158
+ [identifier, admission["label"], json.dumps(scopes), time.time()],
159
+ )
160
+ await store.execute(
161
+ "INSERT INTO external_identities VALUES(?,?,?)",
162
+ [issuer, subject, identifier],
163
+ )
164
+ user = await self.user(identifier, store)
165
+ actor = self.principal(user)
166
+ now = time.time()
167
+ expiry = min(now + self.auth.lifetime, user["expires_at"] or float("inf"))
168
+ token = "tf_user_" + secrets.token_urlsafe(32)
169
+ await store.execute(
170
+ "INSERT INTO user_sessions(digest,user_id,created_at,absolute_expires,last_activity) VALUES(?,?,?,?,?)",
171
+ [session_digest(token), user["id"], now, expiry, now],
172
+ )
173
+ return {"token": token, "expires_at": expiry, "principal": actor.model_dump()}
174
+
175
+ async def resolve(self, params):
176
+ token = params.get("token")
177
+ if not isinstance(token, str) or len(token) > 256:
178
+ raise PluginError("session_invalid", "Sign in again")
179
+ rows = await self.store.query(
180
+ "SELECT * FROM user_sessions WHERE digest=?", [session_digest(token)]
181
+ )
182
+ if not rows:
183
+ raise PluginError("session_invalid", "Sign in again")
184
+ session, now = rows[0], time.time()
185
+ if (
186
+ session["invalidated"]
187
+ or now >= session["absolute_expires"]
188
+ or now >= session["last_activity"] + self.auth.idle
189
+ ):
190
+ raise PluginError("session_invalid", "Sign in again")
191
+ try:
192
+ actor = self.principal(await self.user(session["user_id"]))
193
+ except PluginError:
194
+ raise PluginError("session_invalid", "Sign in again") from None
195
+ if params.get("activity", False):
196
+ await self.store.execute(
197
+ "UPDATE user_sessions SET last_activity=? WHERE digest=?",
198
+ [now, session["digest"]],
199
+ )
200
+ return {"principal": actor.model_dump()}
201
+
202
+ async def invoke(self, method, params):
203
+ if method == "federated_login":
204
+ return await self.login(params)
205
+ if method == "users":
206
+ actor = self.administrator()
207
+ rows = await self.store.query(
208
+ "SELECT * FROM users ORDER BY created_at DESC"
209
+ )
210
+ return {
211
+ "users": [
212
+ public(r)
213
+ for r in rows
214
+ if actor.unrestricted
215
+ or actor.allows(
216
+ json.loads(r["scopes"]),
217
+ self.context.call_info.get("scope_catalog", {}),
218
+ )
219
+ ]
220
+ }
221
+ if method == "user_update":
222
+ actor = self.administrator()
223
+ user = await self.user(params.get("id"))
224
+ scopes = self.scopes(params.get("scopes"))
225
+ expiry, disabled = params.get("expires_at"), params.get("disabled", False)
226
+ if not isinstance(disabled, bool) or (
227
+ expiry is not None
228
+ and (
229
+ type(expiry) not in (int, float)
230
+ or not math.isfinite(expiry)
231
+ or expiry <= time.time()
232
+ )
233
+ ):
234
+ raise PluginError(
235
+ "invalid_request", "Supply a valid user expiry and disabled flag"
236
+ )
237
+ self.auth.bounds(
238
+ actor, json.loads(user["scopes"]), False, user["expires_at"]
239
+ )
240
+ self.auth.bounds(actor, scopes, False, expiry)
241
+ async with self.store.transaction() as store:
242
+ await store.execute(
243
+ "UPDATE users SET scopes=?,expires_at=?,disabled=? WHERE id=?",
244
+ [json.dumps(scopes), expiry, int(disabled), user["id"]],
245
+ )
246
+ if disabled:
247
+ await store.execute(
248
+ "UPDATE user_sessions SET invalidated=1 WHERE user_id=?",
249
+ [user["id"]],
250
+ )
251
+ await store.execute(
252
+ "UPDATE agent_grants SET revoked_at=COALESCE(revoked_at,?) WHERE user_id=?",
253
+ [time.time(), user["id"]],
254
+ )
255
+ return {"user": public(await self.user(user["id"]))}
256
+ if method == "grant_create":
257
+ self.trusted_provider()
258
+ user = await self.user(params.get("user_id"))
259
+ actor = self.principal(user)
260
+ scopes = self.scopes(params.get("scopes"), business=True)
261
+ expiry = params.get("expires_at")
262
+ if (
263
+ not scopes
264
+ or type(expiry) not in (int, float)
265
+ or not math.isfinite(expiry)
266
+ or not time.time() < expiry <= time.time() + 31536000
267
+ ):
268
+ raise PluginError(
269
+ "invalid_request",
270
+ "Supply business scopes and a bounded grant expiry",
271
+ )
272
+ if not all(
273
+ text(params.get(k))
274
+ for k in ("issuer", "client_id", "client_name", "resource")
275
+ ):
276
+ raise PluginError(
277
+ "invalid_request", "Supply the client, issuer and resource"
278
+ )
279
+ self.auth.bounds(actor, scopes, False, expiry)
280
+ identifier = uuid.uuid4().hex
281
+ await self.store.execute(
282
+ "INSERT INTO agent_grants(id,user_id,issuer,client_id,client_name,resource,scopes,created_at,expires_at) VALUES(?,?,?,?,?,?,?,?,?)",
283
+ [
284
+ identifier,
285
+ user["id"],
286
+ params["issuer"],
287
+ params["client_id"],
288
+ params["client_name"],
289
+ params["resource"],
290
+ json.dumps(scopes),
291
+ time.time(),
292
+ expiry,
293
+ ],
294
+ )
295
+ return {"id": identifier}
296
+ if method == "grant_check":
297
+ self.trusted_provider()
298
+ if not text(params.get("id"), 128):
299
+ raise PluginError("invalid_credentials", "Grant is unavailable")
300
+ rows = await self.store.query(
301
+ "SELECT * FROM agent_grants WHERE id=?", [params.get("id")]
302
+ )
303
+ if not rows:
304
+ raise PluginError("invalid_credentials", "Grant is unavailable")
305
+ grant = rows[0]
306
+ user = await self.user(grant["user_id"])
307
+ actor = self.principal(user)
308
+ if grant["revoked_at"] is not None or grant["expires_at"] <= time.time():
309
+ raise PluginError("invalid_credentials", "Grant is unavailable")
310
+ scopes = self.scopes(json.loads(grant["scopes"]), business=True)
311
+ # Permission reductions affect existing grants without issuing new tokens.
312
+ scopes = [s for s in scopes if s in actor.scopes]
313
+ return {
314
+ "grant": {
315
+ **public(grant),
316
+ "scopes": scopes,
317
+ "expires_at": min(
318
+ grant["expires_at"], user["expires_at"] or float("inf")
319
+ ),
320
+ }
321
+ }
322
+ if method == "grants":
323
+ actor = self.actor()
324
+ if actor.kind != "user" or not actor.user_id:
325
+ raise PluginError("forbidden", "Sign in with a user identity")
326
+ self.active(await self.user(actor.user_id))
327
+ rows = await self.store.query(
328
+ "SELECT * FROM agent_grants WHERE user_id=? ORDER BY created_at DESC",
329
+ [actor.user_id],
330
+ )
331
+ return {"grants": [public(r) for r in rows]}
332
+ if method == "revoke_grant":
333
+ if not text(params.get("id"), 128):
334
+ raise PluginError("invalid_request", "Unknown grant")
335
+ rows = await self.store.query(
336
+ "SELECT * FROM agent_grants WHERE id=?", [params.get("id")]
337
+ )
338
+ if not rows:
339
+ raise PluginError("invalid_request", "Unknown grant")
340
+ if self.context.call_info.get("owner") != self.context.config.get(
341
+ "identity_provider", "oidc-auth"
342
+ ):
343
+ actor = self.actor()
344
+ if not actor.unrestricted and not (
345
+ actor.kind == "user" and actor.user_id == rows[0]["user_id"]
346
+ ):
347
+ raise PluginError(
348
+ "forbidden", "You can only revoke your own grants"
349
+ )
350
+ await self.store.execute(
351
+ "UPDATE agent_grants SET revoked_at=COALESCE(revoked_at,?) WHERE id=?",
352
+ [time.time(), rows[0]["id"]],
353
+ )
354
+ return {"revoked": True}
355
+ raise PluginError("invalid_request", "Unknown identity operation")
@@ -0,0 +1,14 @@
1
+
2
+ CREATE TABLE credentials (
3
+ id TEXT PRIMARY KEY, label TEXT NOT NULL, lookup TEXT NOT NULL,
4
+ salt TEXT NOT NULL, verifier TEXT NOT NULL, created_at DOUBLE PRECISION NOT NULL,
5
+ expires_at DOUBLE PRECISION, revoked_at DOUBLE PRECISION, scopes TEXT NOT NULL,
6
+ all_business INTEGER NOT NULL, last_login DOUBLE PRECISION, last_used DOUBLE PRECISION
7
+ );
8
+ CREATE INDEX credentials_lookup ON credentials(lookup);
9
+ CREATE TABLE sessions (
10
+ digest TEXT PRIMARY KEY, credential_id TEXT NOT NULL REFERENCES credentials(id),
11
+ created_at DOUBLE PRECISION NOT NULL, absolute_expires DOUBLE PRECISION NOT NULL,
12
+ last_activity DOUBLE PRECISION NOT NULL, invalidated INTEGER NOT NULL DEFAULT 0
13
+ );
14
+ CREATE INDEX sessions_credential ON sessions(credential_id);
@@ -0,0 +1,22 @@
1
+
2
+ CREATE TABLE users (
3
+ id TEXT PRIMARY KEY, label TEXT NOT NULL, scopes TEXT NOT NULL,
4
+ created_at DOUBLE PRECISION NOT NULL, expires_at DOUBLE PRECISION, disabled INTEGER NOT NULL DEFAULT 0
5
+ );
6
+ CREATE TABLE external_identities (
7
+ issuer TEXT NOT NULL, subject TEXT NOT NULL, user_id TEXT NOT NULL REFERENCES users(id),
8
+ PRIMARY KEY(issuer,subject)
9
+ );
10
+ CREATE TABLE user_sessions (
11
+ digest TEXT PRIMARY KEY, user_id TEXT NOT NULL REFERENCES users(id),
12
+ created_at DOUBLE PRECISION NOT NULL, absolute_expires DOUBLE PRECISION NOT NULL, last_activity DOUBLE PRECISION NOT NULL,
13
+ invalidated INTEGER NOT NULL DEFAULT 0
14
+ );
15
+ CREATE INDEX user_sessions_user ON user_sessions(user_id);
16
+ CREATE TABLE agent_grants (
17
+ id TEXT PRIMARY KEY, user_id TEXT NOT NULL REFERENCES users(id),
18
+ issuer TEXT NOT NULL, client_id TEXT NOT NULL, client_name TEXT NOT NULL,
19
+ resource TEXT NOT NULL, scopes TEXT NOT NULL, created_at DOUBLE PRECISION NOT NULL,
20
+ expires_at DOUBLE PRECISION NOT NULL, revoked_at DOUBLE PRECISION
21
+ );
22
+ CREATE INDEX agent_grants_user ON agent_grants(user_id);
@@ -0,0 +1,497 @@
1
+ """Credential authority. All persistence goes through the managed SQL service."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import hmac
7
+ import json
8
+ import re
9
+ import secrets
10
+ import time
11
+ import uuid
12
+ from importlib.resources import files
13
+
14
+ from toolframe_sdk import (
15
+ AuthorizationSpec,
16
+ MethodSpec,
17
+ Migration,
18
+ Plugin,
19
+ PluginDefinition,
20
+ PluginError,
21
+ Principal,
22
+ Requirement,
23
+ ServiceSpec,
24
+ StoreSchema,
25
+ )
26
+
27
+ from .crypto import lookup, new_verifier, session_digest, verifier
28
+ from .identities import METHODS as IDENTITY_METHODS
29
+ from .identities import SCHEMA as IDENTITY_SCHEMA
30
+ from .identities import IdentityAuthority
31
+
32
+ SERVICE = "toolframe.auth"
33
+ SCHEMA = """
34
+ CREATE TABLE credentials (
35
+ id TEXT PRIMARY KEY, label TEXT NOT NULL, lookup TEXT NOT NULL,
36
+ salt TEXT NOT NULL, verifier TEXT NOT NULL, created_at REAL NOT NULL,
37
+ expires_at REAL, revoked_at REAL, scopes TEXT NOT NULL,
38
+ all_business INTEGER NOT NULL, last_login REAL, last_used REAL
39
+ );
40
+ CREATE INDEX credentials_lookup ON credentials(lookup);
41
+ CREATE TABLE sessions (
42
+ digest TEXT PRIMARY KEY, credential_id TEXT NOT NULL REFERENCES credentials(id),
43
+ created_at REAL NOT NULL, absolute_expires REAL NOT NULL,
44
+ last_activity REAL NOT NULL, invalidated INTEGER NOT NULL DEFAULT 0
45
+ );
46
+ CREATE INDEX sessions_credential ON sessions(credential_id);
47
+ """
48
+ EXPECTED_ERRORS = {
49
+ "invalid_credentials",
50
+ "session_invalid",
51
+ "password_conflict",
52
+ "credential_missing",
53
+ "credential_revoked",
54
+ "invalid_request",
55
+ "forbidden",
56
+ "rate_limited",
57
+ }
58
+
59
+
60
+ def valid(record, now):
61
+ return record["revoked_at"] is None and (
62
+ record["expires_at"] is None or record["expires_at"] > now
63
+ )
64
+
65
+
66
+ def valid_text(value):
67
+ if not isinstance(value, str):
68
+ return False
69
+ try:
70
+ value.encode("utf-8")
71
+ return True
72
+ except UnicodeError:
73
+ return False
74
+
75
+
76
+ def principal(record):
77
+ return Principal(
78
+ kind="password",
79
+ credential_id=record["id"],
80
+ scopes=tuple(json.loads(record["scopes"])),
81
+ all_business=bool(record["all_business"]),
82
+ expires_at=record["expires_at"],
83
+ )
84
+
85
+
86
+ def public_record(record):
87
+ return {
88
+ key: value
89
+ for key, value in record.items()
90
+ if key not in {"lookup", "salt", "verifier"}
91
+ } | {
92
+ "scopes": json.loads(record["scopes"]),
93
+ "all_business": bool(record["all_business"]),
94
+ }
95
+
96
+
97
+ class AuthProvider(Plugin):
98
+ def __init__(self, context):
99
+ super().__init__(context)
100
+ self.lock = asyncio.Lock()
101
+ self.key = None
102
+ self.store = context.storage()
103
+ self.idle = context.config.get("session_idle_seconds", 86400)
104
+ self.lifetime = context.config.get("session_max_seconds", 604800)
105
+ self.pending_hashes = 0
106
+ self.identities = IdentityAuthority(self)
107
+
108
+ async def activate(self):
109
+ self.key = bytes.fromhex(self.context.private_secrets["password-lookup"])
110
+ # Probe read is allowed during activation; host already ensured the schema.
111
+ await self.store.query("SELECT id FROM credentials LIMIT 1")
112
+
113
+ async def rows(self, sql, params=(), store=None):
114
+ return await (store or self.store).query(sql, params)
115
+
116
+ async def get(self, identifier, store=None):
117
+ rows = await self.rows(
118
+ "SELECT * FROM credentials WHERE id=?", [identifier], store
119
+ )
120
+ if not rows:
121
+ raise PluginError("credential_missing", "Access password record not found")
122
+ return rows[0]
123
+
124
+ def actor(self):
125
+ value = self.context.call_info.get("principal")
126
+ if not value:
127
+ raise PluginError("forbidden", "A host-admitted administrator is required")
128
+ actor = Principal.model_validate(value)
129
+ if not actor.unrestricted and "system.auth.passwords" not in actor.scopes:
130
+ raise PluginError("forbidden", "Password management scope required")
131
+ return actor
132
+
133
+ def bounds(self, actor, scopes, all_business, expires_at):
134
+ if actor.unrestricted:
135
+ return
136
+ catalog = self.context.call_info.get("scope_catalog", {})
137
+ if (all_business and not actor.all_business) or not actor.allows(
138
+ scopes, catalog
139
+ ):
140
+ raise PluginError(
141
+ "forbidden", "Cannot delegate scopes beyond your own grant"
142
+ )
143
+ if actor.expires_at is not None and (
144
+ expires_at is None or expires_at > actor.expires_at
145
+ ):
146
+ raise PluginError(
147
+ "forbidden", "Cannot delegate beyond your password expiry"
148
+ )
149
+
150
+ def fields(self, params):
151
+ label, scopes = params.get("label", ""), params.get("scopes", [])
152
+ expiry, all_business = (
153
+ params.get("expires_at"),
154
+ params.get("all_business", False),
155
+ )
156
+ catalog = self.context.call_info.get("scope_catalog", {})
157
+ if (
158
+ not valid_text(label)
159
+ or not label.strip()
160
+ or len(label) > 120
161
+ or not isinstance(scopes, list)
162
+ or not all(isinstance(x, str) and x in catalog for x in scopes)
163
+ or not isinstance(all_business, bool)
164
+ or (
165
+ expiry is not None
166
+ and (
167
+ isinstance(expiry, bool)
168
+ or not isinstance(expiry, (int, float))
169
+ or not time.time() < expiry < 253402300800
170
+ )
171
+ )
172
+ ):
173
+ raise PluginError(
174
+ "invalid_request",
175
+ "Supply a label, known scopes and a future expiry (or null)",
176
+ )
177
+ return label.strip(), sorted(set(scopes)), all_business, expiry
178
+
179
+ async def hash_work(self, function, *args):
180
+ # Reject excess work before submitting to the thread pool; no unbounded queue.
181
+ if self.pending_hashes >= 2:
182
+ raise PluginError("rate_limited", "Password verifier is busy; retry later")
183
+ self.pending_hashes += 1
184
+ task = asyncio.create_task(asyncio.to_thread(function, *args))
185
+ try:
186
+ return await asyncio.shield(task)
187
+ finally:
188
+ # Cancellation cannot release the memory budget before scrypt finishes.
189
+ if not task.done():
190
+ await asyncio.shield(task)
191
+ self.pending_hashes -= 1
192
+
193
+ async def invoke(self, service, method, params):
194
+ if method == "login":
195
+ return await self.login(params)
196
+ if method == "create":
197
+ return await self.create(params)
198
+ async with self.lock:
199
+ if method in IDENTITY_METHODS:
200
+ return await self.identities.invoke(method, params)
201
+ if method == "resolve":
202
+ if isinstance(params.get("token"), str) and params["token"].startswith(
203
+ "tf_user_"
204
+ ):
205
+ return await self.identities.resolve(params)
206
+ return await self.resolve(params)
207
+ if method == "logout":
208
+ await self.store.execute(
209
+ "UPDATE sessions SET invalidated=1 WHERE digest=?",
210
+ [session_digest(params["token"])],
211
+ )
212
+ await self.store.execute(
213
+ "UPDATE user_sessions SET invalidated=1 WHERE digest=?",
214
+ [session_digest(params["token"])],
215
+ )
216
+ return {}
217
+ actor = self.actor()
218
+ if method == "list":
219
+ records = await self.rows(
220
+ "SELECT * FROM credentials ORDER BY created_at DESC"
221
+ )
222
+ result = []
223
+ for record in records:
224
+ try:
225
+ self.bounds(
226
+ actor,
227
+ json.loads(record["scopes"]),
228
+ record["all_business"],
229
+ record["expires_at"],
230
+ )
231
+ except PluginError:
232
+ continue
233
+ result.append(public_record(record))
234
+ return {"credentials": result}
235
+ if method in {"update", "revoke"}:
236
+ if not isinstance(params.get("id"), str) or not re.fullmatch(
237
+ r"[0-9a-f]{32}", params["id"]
238
+ ):
239
+ raise PluginError(
240
+ "invalid_request", "Supply a credential record ID"
241
+ )
242
+ async with self.store.transaction() as store:
243
+ record = await self.get(params.get("id"), store)
244
+ self.bounds(
245
+ actor,
246
+ json.loads(record["scopes"]),
247
+ record["all_business"],
248
+ record["expires_at"],
249
+ )
250
+ if method == "revoke":
251
+ await store.execute(
252
+ "UPDATE credentials SET revoked_at=COALESCE(revoked_at,?) WHERE id=?",
253
+ [time.time(), record["id"]],
254
+ )
255
+ else:
256
+ if record["revoked_at"] is not None:
257
+ raise PluginError(
258
+ "credential_revoked",
259
+ "Create a new password record instead",
260
+ )
261
+ label, scopes, all_business, expiry = self.fields(params)
262
+ self.bounds(actor, scopes, all_business, expiry)
263
+ await self.unique(
264
+ record["lookup"], exclude=record["id"], store=store
265
+ )
266
+ await store.execute(
267
+ "UPDATE credentials SET label=?,scopes=?,all_business=?,expires_at=? WHERE id=?",
268
+ [
269
+ label,
270
+ json.dumps(scopes),
271
+ int(all_business),
272
+ expiry,
273
+ record["id"],
274
+ ],
275
+ )
276
+ # Grant/expiry changes require a fresh login. Revocation is immediate.
277
+ await store.execute(
278
+ "UPDATE sessions SET invalidated=1 WHERE credential_id=?",
279
+ [record["id"]],
280
+ )
281
+ return public_record(await self.get(record["id"], store))
282
+ raise PluginError("invalid_request", "Unknown auth operation")
283
+
284
+ async def unique(self, index, *, exclude="", store=None):
285
+ rows = await self.rows(
286
+ "SELECT id FROM credentials WHERE lookup=? AND id<>? AND revoked_at IS NULL AND (expires_at IS NULL OR expires_at>?)",
287
+ [index, exclude, time.time()],
288
+ store,
289
+ )
290
+ if rows:
291
+ raise PluginError(
292
+ "password_conflict", "This password already has an active authorization"
293
+ )
294
+
295
+ async def create(self, params):
296
+ actor = self.actor()
297
+ label, scopes, all_business, expiry = self.fields(params)
298
+ self.bounds(actor, scopes, all_business, expiry)
299
+ secret = params.get("password")
300
+ generated = secret is None
301
+ if generated:
302
+ secret = secrets.token_urlsafe(24)
303
+ if not valid_text(secret) or not 8 <= len(secret) <= 32:
304
+ raise PluginError(
305
+ "invalid_request", "Passwords must contain 8–32 characters"
306
+ )
307
+ index = lookup(self.key, secret)
308
+ salt, encoded = await self.hash_work(new_verifier, secret)
309
+ async with self.lock, self.store.transaction() as store:
310
+ await self.unique(index, store=store)
311
+ first = not await self.rows(
312
+ "SELECT id FROM credentials LIMIT 1", store=store
313
+ )
314
+ identifier = uuid.uuid4().hex
315
+ await store.execute(
316
+ "INSERT INTO credentials(id,label,lookup,salt,verifier,created_at,expires_at,scopes,all_business) VALUES(?,?,?,?,?,?,?,?,?)",
317
+ [
318
+ identifier,
319
+ label,
320
+ index,
321
+ salt,
322
+ encoded,
323
+ time.time(),
324
+ expiry,
325
+ json.dumps(scopes),
326
+ int(all_business),
327
+ ],
328
+ )
329
+ result = public_record(await self.get(identifier, store))
330
+ return {
331
+ "credential": result,
332
+ "first_password": first,
333
+ "password": secret if generated else None,
334
+ }
335
+
336
+ async def login(self, params):
337
+ secret = params.get("password")
338
+ if not valid_text(secret) or not 1 <= len(secret) <= 1024:
339
+ raise PluginError("invalid_credentials", "Invalid password")
340
+ # Unique active lookup is serialized with create/extend/revoke.
341
+ async with self.lock:
342
+ records = await self.rows(
343
+ "SELECT * FROM credentials WHERE lookup=? AND revoked_at IS NULL AND (expires_at IS NULL OR expires_at>?)",
344
+ [lookup(self.key, secret), time.time()],
345
+ )
346
+ record = records[0] if len(records) == 1 else None
347
+ # Dummy verification makes unknown/expired passwords take the same hash work.
348
+ salt = record["salt"] if record else "00" * 16
349
+ result = await self.hash_work(verifier, secret, salt)
350
+ if record is None or not hmac.compare_digest(result, record["verifier"]):
351
+ raise PluginError("invalid_credentials", "Invalid password")
352
+ async with self.lock, self.store.transaction() as store:
353
+ record = await self.get(record["id"], store)
354
+ now = time.time()
355
+ if not valid(record, now):
356
+ raise PluginError("invalid_credentials", "Invalid password")
357
+ token = secrets.token_urlsafe(32)
358
+ expires = min(now + self.lifetime, record["expires_at"] or float("inf"))
359
+ await store.execute(
360
+ "INSERT INTO sessions(digest,credential_id,created_at,absolute_expires,last_activity) VALUES(?,?,?,?,?)",
361
+ [session_digest(token), record["id"], now, expires, now],
362
+ )
363
+ await store.execute(
364
+ "UPDATE credentials SET last_login=?,last_used=? WHERE id=?",
365
+ [now, now, record["id"]],
366
+ )
367
+ return {
368
+ "token": token,
369
+ "expires_at": expires,
370
+ "principal": principal(record).model_dump(),
371
+ }
372
+
373
+ async def resolve(self, params):
374
+ token = params.get("token", "")
375
+ if not valid_text(token) or len(token) > 256:
376
+ raise PluginError("session_invalid", "Sign in again")
377
+ sessions = await self.rows(
378
+ "SELECT * FROM sessions WHERE digest=?", [session_digest(token)]
379
+ )
380
+ if not sessions:
381
+ raise PluginError("session_invalid", "Sign in again")
382
+ session = sessions[0]
383
+ record = await self.get(session["credential_id"])
384
+ now = time.time()
385
+ if (
386
+ session["invalidated"]
387
+ or now >= session["absolute_expires"]
388
+ or now >= session["last_activity"] + self.idle
389
+ or not valid(record, now)
390
+ ):
391
+ if not session["invalidated"]:
392
+ await self.store.execute(
393
+ "UPDATE sessions SET invalidated=1 WHERE digest=?",
394
+ [session["digest"]],
395
+ )
396
+ raise PluginError("session_invalid", "Sign in again")
397
+ if params.get("activity", False):
398
+ async with self.store.transaction() as store:
399
+ await store.execute(
400
+ "UPDATE sessions SET last_activity=? WHERE digest=?",
401
+ [now, session["digest"]],
402
+ )
403
+ await store.execute(
404
+ "UPDATE credentials SET last_used=? WHERE id=?", [now, record["id"]]
405
+ )
406
+ return {"principal": principal(record).model_dump()}
407
+
408
+
409
+ plugin = PluginDefinition(
410
+ id="auth",
411
+ kind="provider",
412
+ provider_kind="auth",
413
+ factory="toolframe_auth.plugin:AuthProvider",
414
+ authorization=AuthorizationSpec(),
415
+ private_secrets=("password-lookup",),
416
+ requires={"storage": Requirement(service="toolframe.storage.sql")},
417
+ services={
418
+ SERVICE: ServiceSpec(
419
+ methods={
420
+ name: MethodSpec(audience="internal")
421
+ for name in (
422
+ "login",
423
+ "resolve",
424
+ "logout",
425
+ "create",
426
+ "list",
427
+ "update",
428
+ "revoke",
429
+ *IDENTITY_METHODS,
430
+ )
431
+ }
432
+ )
433
+ },
434
+ config_schema={
435
+ "type": "object",
436
+ "properties": {
437
+ "identity_provider": {
438
+ "type": "string",
439
+ "pattern": "^[a-z][a-z0-9-]{0,63}$",
440
+ },
441
+ "federated_identities": {
442
+ "type": "array",
443
+ "maxItems": 10000,
444
+ "items": {
445
+ "type": "object",
446
+ "additionalProperties": False,
447
+ "required": ["issuer", "subject", "label", "scopes"],
448
+ "properties": {
449
+ "issuer": {"type": "string", "minLength": 1, "maxLength": 2048},
450
+ "subject": {"type": "string", "minLength": 1, "maxLength": 255},
451
+ "label": {"type": "string", "minLength": 1, "maxLength": 120},
452
+ "scopes": {
453
+ "type": "array",
454
+ "items": {"type": "string"},
455
+ "uniqueItems": True,
456
+ },
457
+ },
458
+ },
459
+ },
460
+ "session_idle_seconds": {
461
+ "type": "integer",
462
+ "minimum": 1,
463
+ "maximum": 31536000,
464
+ },
465
+ "session_max_seconds": {
466
+ "type": "integer",
467
+ "minimum": 1,
468
+ "maximum": 31536000,
469
+ },
470
+ },
471
+ "additionalProperties": False,
472
+ },
473
+ store=StoreSchema(
474
+ revision="v2",
475
+ migrations=(
476
+ Migration(
477
+ revision="v1",
478
+ sql=SCHEMA,
479
+ dialects={
480
+ "postgresql": files(__package__)
481
+ .joinpath("migrations", "v1.postgresql.sql")
482
+ .read_text()
483
+ },
484
+ ),
485
+ Migration(
486
+ revision="v2",
487
+ parent="v1",
488
+ sql=IDENTITY_SCHEMA,
489
+ dialects={
490
+ "postgresql": files(__package__)
491
+ .joinpath("migrations", "v2.postgresql.sql")
492
+ .read_text()
493
+ },
494
+ ),
495
+ ),
496
+ ),
497
+ )
@@ -0,0 +1,129 @@
1
+ Metadata-Version: 2.5
2
+ Name: toolframe-auth
3
+ Version: 0.2.0
4
+ Summary: Managed access passwords and sessions for Toolframe
5
+ Project-URL: Homepage, https://github.com/toolframe/toolframe-auth
6
+ Project-URL: Repository, https://github.com/toolframe/toolframe-auth
7
+ Project-URL: Documentation, https://github.com/toolframe/toolframe-auth#readme
8
+ Project-URL: Issues, https://github.com/toolframe/toolframe-auth/issues
9
+ Author-email: byfb <62798989+byfb@users.noreply.github.com>
10
+ License-Expression: Apache-2.0
11
+ License-File: LICENSE
12
+ License-File: NOTICE
13
+ Requires-Python: >=3.14
14
+ Requires-Dist: toolframe-sdk==0.3.0
15
+ Description-Content-Type: text/markdown
16
+
17
+ # Toolframe Auth
18
+
19
+ Authentication and grant decisions for access passwords, federated users and
20
+ revocable agent delegation. This provider owns `auth`'s managed SQL store; it never opens
21
+ database files itself. It requires SDK 0.3.0 and `toolframe.storage.sql`.
22
+
23
+ ## Install
24
+
25
+ With a running Toolframe application and an active SQL storage provider:
26
+
27
+ ```sh
28
+ toolframe --home APP plugin add pypi:toolframe-auth==0.2.0 --enable
29
+ ```
30
+
31
+ The [Entry Register template](https://github.com/toolframe/toolframe-core#readme)
32
+ includes Auth and Dashboard Auth. The host resolves the SDK and the plugin's
33
+ isolated environment automatically.
34
+
35
+ Core supplies the private `password-lookup` key separately from configuration.
36
+ Credential records store a keyed HMAC-SHA256 lookup plus a per-record salted
37
+ scrypt verifier (`N=131072`, `r=8`, `p=1`, 32-byte output). At most two hashes run
38
+ concurrently. Core also limits login attempts. Sessions use random opaque tokens;
39
+ only SHA-256 digests of those high-entropy tokens are persisted. Metadata/list
40
+ responses exclude lookup values, salts and verifiers.
41
+
42
+ The internal `toolframe.auth` service implements login, resolve/touch, logout,
43
+ create/list/update/revoke. Core admits administrators and passes their trusted
44
+ principal/catalog. These methods are not directly published business APIs.
45
+ `toolframe-dashboard-auth` supplies presentation through core's protected API.
46
+
47
+ New passwords accept 8–32 characters; omitted passwords generate a random
48
+ 32-character secret. Existing longer passwords issued by 0.1.0 can still log in.
49
+ The password-length policy preserves existing password records and sessions.
50
+
51
+ ## Federated users and agent grants
52
+
53
+ Enable `toolframe-oidc-auth` for OIDC login. Auth remains the local identity and
54
+ permission authority; it does not implement provider discovery or OAuth endpoints.
55
+ Configure the trusted plugin ID with `identity_provider` (default `oidc-auth`) and
56
+ initial admission with exact `federated_identities` entries:
57
+
58
+ ```toml
59
+ [plugins.auth.config]
60
+ identity_provider = "oidc-auth"
61
+ federated_identities = [
62
+ { issuer = "https://accounts.google.com", subject = "VERIFIED_SUB", label = "Alice", scopes = ["notes.read"] },
63
+ ]
64
+ ```
65
+
66
+ The trusted plugin must supply verified issuer/subject claims. No email matching
67
+ or automatic account merging occurs. The admission entry creates a local user
68
+ once; later permission/disablement changes use the protected user-management API.
69
+ Changing admission configuration does not overwrite existing users. Every user
70
+ gets `system.auth.self`; `system.auth.users` permits bounded administration.
71
+
72
+ The internal service additionally implements `federated_login`, `users`,
73
+ `user_update`, `grant_create`, `grant_check`, `grants` and `revoke_grant`.
74
+ Core verifies administrative/self-service callers; only the configured identity
75
+ provider may admit external identities or issue/check delegated grants.
76
+ Agent grants include user, issuer, client, resource, explicit business scopes and
77
+ expiry. Grant checks intersect current user permissions. Revocation does not end
78
+ the browser session; disabling a user invalidates sessions and revokes all their
79
+ agent grants. Password and MCP-key credentials retain their independent behavior.
80
+
81
+ This feature introduces additive **store revision v2**. Existing v1 stores require
82
+ Core's explicit `migrate plan auth` / `migrate apply auth --plan-id ...` workflow
83
+ after staging a compatible Auth build. Back up the store and retained secrets
84
+ first. The migration leaves existing password/session tables intact.
85
+
86
+ Active secret uniqueness is transactional. Expired/revoked secrets can be reused
87
+ in a new record with a new grant; old sessions remain tied to the old record.
88
+ Revoked records cannot be restored. Editing a grant invalidates its sessions.
89
+ Delegation is limited by the administrator's own scopes, dynamic-business selector
90
+ and expiry. Issued grants do not inherit a revocation dependency on their creator.
91
+
92
+ Configuration: `session_max_seconds` defaults to 604800; `session_idle_seconds`
93
+ defaults to 86400. Password expiry caps both. Successful logins and authorized
94
+ functional activity update usage; polling and denied attempts do not.
95
+
96
+ Back up the consistent auth SQLite store and retained private key together. A
97
+ missing key with an existing store is a recovery error, not a reason to regenerate
98
+ the key. Removing/reloading the plugin retains both. Runtime validation uses
99
+ temporary storage and secrets.
100
+
101
+ ```sh
102
+ uv sync
103
+ uv run pytest -q
104
+ uv run ruff check src tests
105
+ uv build --wheel
106
+ ```
107
+
108
+ For the same isolated lint, tests, distribution and wheel-install checks used by
109
+ GitHub Actions, run `python3.14 scripts/ci.py`. See [CI and publishing](docs/ci.md)
110
+ for pinned sibling sources, local requirements and TestPyPI/PyPI setup.
111
+
112
+ Core owns access policy. Its compatible OIDC integration supports
113
+ `access.failure_mode = "closed"` for protected deployments; the default preserves
114
+ legacy public business fallback. MCP, llms and explicitly public business APIs
115
+ have independent policies.
116
+
117
+ For release validation and Trusted Publisher setup, see [releasing](docs/releasing.md).
118
+
119
+ ## License
120
+
121
+ Licensed under the Apache License, Version 2.0. See [LICENSE](LICENSE) and [NOTICE](NOTICE).
122
+
123
+ ## PostgreSQL storage
124
+
125
+ Version 0.2 requires SDK 0.3 and declares PostgreSQL migration SQL alongside the
126
+ unchanged SQLite history. Provision this plugin’s stable store owner with the
127
+ PostgreSQL provider before enabling it. The application still runs one Core;
128
+ retain its private keys and configuration with the application home. Existing
129
+ SQLite records are not imported automatically.
@@ -0,0 +1,12 @@
1
+ toolframe_auth/__init__.py,sha256=Fi1pOy3Sq42boSaPh5BPWxp3uephua4r6L-bWJ6p_P0,47
2
+ toolframe_auth/crypto.py,sha256=2FQroy58arAu5-gtIpgcF8_xjLIBCtbsMoVWebVOjKY,685
3
+ toolframe_auth/identities.py,sha256=q1idkMrmiM2v425LXcfcuHD8lYINp9s3iPlsHq-oB1o,14385
4
+ toolframe_auth/plugin.py,sha256=S0LCa4YQw5zGc1foPG06_WEC19RCGIw1-582S0PYYOw,18989
5
+ toolframe_auth/migrations/v1.postgresql.sql,sha256=plTp_P-urHRDA_6EHhJ9_zGYVT_s2nflMiOqK5UUcXA,738
6
+ toolframe_auth/migrations/v2.postgresql.sql,sha256=8D-RtlAx965JmUa7jF9SXkiYMv9ehj85_fTZHpwFXCE,1057
7
+ toolframe_auth-0.2.0.dist-info/METADATA,sha256=KJomdS--HqnWwRCXbHVCH05acjPtF507WjS0Wh0on2k,6216
8
+ toolframe_auth-0.2.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
9
+ toolframe_auth-0.2.0.dist-info/entry_points.txt,sha256=Dbns662YpIQPQN9T-MypGViWkHxKsuArqUKxqagEhOI,56
10
+ toolframe_auth-0.2.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
11
+ toolframe_auth-0.2.0.dist-info/licenses/NOTICE,sha256=cmOwtaBn-GZfDGPMQQuvCLRVnnuD41REN1cDLuzc9yI,35
12
+ toolframe_auth-0.2.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.32.4
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [toolframe.plugins]
2
+ auth = toolframe_auth.plugin:plugin
@@ -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.
@@ -0,0 +1,2 @@
1
+ toolframe-auth
2
+ Copyright 2026 byfb