authfn 0.1.0__tar.gz

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,76 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ pip-wheel-metadata/
24
+ share/python-wheels/
25
+ *.egg-info/
26
+ .installed.cfg
27
+ *.egg
28
+ MANIFEST
29
+
30
+ # PyInstaller
31
+ *.manifest
32
+ *.spec
33
+
34
+ # Unit test / coverage reports
35
+ htmlcov/
36
+ .tox/
37
+ .nox/
38
+ .coverage
39
+ .coverage.*
40
+ .cache
41
+ nosetests.xml
42
+ coverage.xml
43
+ *.cover
44
+ *.py,cover
45
+ .hypothesis/
46
+ .pytest_cache/
47
+
48
+ # Environments
49
+ .env
50
+ .venv
51
+ env/
52
+ venv/
53
+ ENV/
54
+ env.bak/
55
+ venv.bak/
56
+
57
+ # IDEs
58
+ .vscode/
59
+ .idea/
60
+ *.swp
61
+ *.swo
62
+ *~
63
+
64
+ # mypy
65
+ .mypy_cache/
66
+ .dmypy.json
67
+ dmypy.json
68
+
69
+ # Pyre type checker
70
+ .pyre/
71
+
72
+ # pytype static type analyzer
73
+ .pytype/
74
+
75
+ # Cython debug symbols
76
+ cython_debug/
@@ -0,0 +1,85 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ## [Unreleased]
9
+
10
+ ### Added
11
+ - Nothing yet
12
+
13
+ ### Changed
14
+ - Nothing yet
15
+
16
+ ### Fixed
17
+ - Nothing yet
18
+
19
+ ## [0.1.0] - 2026-01-12
20
+
21
+ ### Added
22
+ - Initial release of authfn Python SDK
23
+ - API key generation with cryptographically secure random generation
24
+ - Authentication via Bearer token
25
+ - Authorization for resource-based access control
26
+ - Key revocation support
27
+ - Key expiration with automatic checking
28
+ - Metadata support for custom key metadata
29
+ - Scopes support for optional scope-based permissions
30
+ - Database abstraction using Protocol-based adapter pattern
31
+ - Schema definition for declarative database table generation
32
+ - Type safety with Pydantic models and runtime validation
33
+ - Full async/await support throughout
34
+ - Custom exception classes for error handling
35
+ - Comprehensive test suite with 11 test cases
36
+ - Mock database adapter for testing
37
+ - Complete documentation:
38
+ - README.md with usage examples
39
+ - INSTALLATION.md with setup instructions
40
+ - COMPARISON.md comparing TypeScript and Python implementations
41
+ - IMPLEMENTATION_SUMMARY.md with implementation details
42
+ - PUBLISHING.md with publishing guide
43
+ - QUICKSTART.md for quick reference
44
+ - Example code in `examples/basic_usage.py`
45
+ - Development tools:
46
+ - pytest configuration
47
+ - mypy type checking
48
+ - ruff linting
49
+ - black formatting
50
+ - Makefile for common tasks
51
+ - Publishing script
52
+
53
+ ### Core Features
54
+ - `AuthFn` class for main functionality
55
+ - `AuthFnProvider` class for authentication and authorization
56
+ - `create_authfn()` factory function
57
+ - `generate_api_key()` for secure key generation
58
+ - `generate_id()` for unique ID generation
59
+
60
+ ### Type Definitions
61
+ - `ApiKeySession` - Session data after authentication
62
+ - `ApiKey` - Complete API key data
63
+ - `ApiKeyCreate` - Input data for creating keys
64
+ - `ApiKeyResponse` - Response with ID and secret key
65
+ - `ApiKeySanitized` - API key without secret
66
+ - `AuthFnConfig` - Configuration model
67
+ - `WhereClause` - Database query clause
68
+ - `OrderByClause` - Database ordering clause
69
+
70
+ ### Protocols
71
+ - `DatabaseAdapter` - Protocol for database implementations
72
+ - `Request` - Protocol for HTTP request objects
73
+ - `AuthProvider` - Protocol for auth providers
74
+
75
+ ### Dependencies
76
+ - pydantic>=2.5.0 - Data validation and type safety
77
+ - cryptography>=41.0.0 - Cryptographic operations
78
+
79
+ ### Python Support
80
+ - Python 3.10+
81
+ - Python 3.11
82
+ - Python 3.12
83
+
84
+ [Unreleased]: https://github.com/21nCo/super-functions/compare/v0.1.0...HEAD
85
+ [0.1.0]: https://github.com/21nCo/super-functions/releases/tag/v0.1.0
@@ -0,0 +1,417 @@
1
+ # TypeScript to Python Implementation Comparison
2
+
3
+ This document compares the TypeScript SDK implementation with the Python SDK implementation.
4
+
5
+ ## Architecture Comparison
6
+
7
+ ### TypeScript Structure
8
+ ```
9
+ authfn/ts-sdk/
10
+ ├── src/
11
+ │ ├── index.ts # Main implementation
12
+ │ ├── types.ts # Type definitions
13
+ │ └── schema.ts # Database schema
14
+ ├── package.json
15
+ └── README.md
16
+ ```
17
+
18
+ ### Python Structure
19
+ ```
20
+ authfn/python/
21
+ ├── authfn/
22
+ │ ├── __init__.py # Public API exports
23
+ │ ├── authfn.py # Main implementation
24
+ │ ├── types.py # Type definitions (Pydantic models)
25
+ │ └── schema.py # Database schema
26
+ ├── tests/
27
+ │ ├── __init__.py
28
+ │ └── test_authfn.py
29
+ ├── examples/
30
+ │ ├── __init__.py
31
+ │ └── basic_usage.py
32
+ ├── pyproject.toml
33
+ ├── setup.py
34
+ ├── LICENSE
35
+ └── README.md
36
+ ```
37
+
38
+ ## Feature Parity
39
+
40
+ ### Core Features
41
+
42
+ | Feature | TypeScript | Python | Notes |
43
+ |---------|-----------|--------|-------|
44
+ | API Key Generation | ✅ | ✅ | Both use cryptographically secure random generation |
45
+ | Authentication | ✅ | ✅ | Bearer token authentication |
46
+ | Authorization | ✅ | ✅ | Resource-based access control |
47
+ | Key Revocation | ✅ | ✅ | Full revocation support |
48
+ | Key Expiration | ✅ | ✅ | Automatic expiration checking |
49
+ | Metadata Support | ✅ | ✅ | Custom metadata per key |
50
+ | Scopes | ✅ | ✅ | Optional scope-based permissions |
51
+ | Database Abstraction | ✅ | ✅ | Adapter pattern for different databases |
52
+ | Schema Definition | ✅ | ✅ | Declarative schema for table generation |
53
+
54
+ ### API Comparison
55
+
56
+ #### Creating an Instance
57
+
58
+ **TypeScript:**
59
+ ```typescript
60
+ import { createAuthFn } from 'authfn';
61
+
62
+ const auth = createAuthFn({
63
+ database: adapter,
64
+ namespace: 'authfn',
65
+ enableApi: true,
66
+ apiConfig: {
67
+ adminKey: process.env.ADMIN_KEY,
68
+ },
69
+ });
70
+ ```
71
+
72
+ **Python:**
73
+ ```python
74
+ from authfn import create_authfn, AuthFnConfig
75
+
76
+ auth = create_authfn(
77
+ AuthFnConfig(
78
+ database=adapter,
79
+ namespace="authfn",
80
+ enable_api=True,
81
+ api_config={
82
+ "admin_key": os.environ.get("ADMIN_KEY"),
83
+ },
84
+ )
85
+ )
86
+ ```
87
+
88
+ #### Creating an API Key
89
+
90
+ **TypeScript:**
91
+ ```typescript
92
+ const result = await auth.createKey({
93
+ name: 'Production Key',
94
+ resourceIds: ['resource-1', 'resource-2'],
95
+ scopes: ['read', 'write'],
96
+ metadata: { env: 'production' },
97
+ expiresAt: new Date('2025-12-31'),
98
+ });
99
+ ```
100
+
101
+ **Python:**
102
+ ```python
103
+ from authfn.types import ApiKeyCreate
104
+
105
+ result = await auth.create_key(
106
+ ApiKeyCreate(
107
+ name="Production Key",
108
+ resourceIds=["resource-1", "resource-2"],
109
+ scopes=["read", "write"],
110
+ metadata={"env": "production"},
111
+ expiresAt=datetime(2025, 12, 31),
112
+ )
113
+ )
114
+ ```
115
+
116
+ #### Authenticating
117
+
118
+ **TypeScript:**
119
+ ```typescript
120
+ const session = await auth.provider.authenticate(request);
121
+ if (session) {
122
+ console.log(`Authenticated as: ${session.name}`);
123
+ }
124
+ ```
125
+
126
+ **Python:**
127
+ ```python
128
+ session = await auth.provider.authenticate(request)
129
+ if session:
130
+ print(f"Authenticated as: {session.name}")
131
+ ```
132
+
133
+ #### Authorizing
134
+
135
+ **TypeScript:**
136
+ ```typescript
137
+ const canAccess = await auth.provider.authorize(session, 'resource-1');
138
+ ```
139
+
140
+ **Python:**
141
+ ```python
142
+ can_access = await auth.provider.authorize(session, "resource-1")
143
+ ```
144
+
145
+ ## Implementation Differences
146
+
147
+ ### Type System
148
+
149
+ **TypeScript:**
150
+ - Uses TypeScript interfaces and types
151
+ - Compile-time type checking
152
+ - JSDoc comments for documentation
153
+
154
+ **Python:**
155
+ - Uses Pydantic models for runtime validation
156
+ - Type hints with Protocol for interfaces
157
+ - Both compile-time (mypy) and runtime validation
158
+ - Automatic JSON serialization/deserialization
159
+
160
+ ### Async/Await
161
+
162
+ **TypeScript:**
163
+ - Native Promise-based async/await
164
+ - Works with Node.js event loop
165
+
166
+ **Python:**
167
+ - Native async/await with asyncio
168
+ - Coroutines and event loop
169
+ - Compatible with ASGI frameworks (FastAPI, Starlette)
170
+
171
+ ### Error Handling
172
+
173
+ **TypeScript:**
174
+ ```typescript
175
+ import {
176
+ InvalidCredentialsError,
177
+ ExpiredCredentialsError
178
+ } from '@superfunctions/auth';
179
+
180
+ try {
181
+ const session = await auth.provider.authenticate(request);
182
+ } catch (error) {
183
+ if (error instanceof InvalidCredentialsError) {
184
+ // Handle invalid credentials
185
+ }
186
+ }
187
+ ```
188
+
189
+ **Python:**
190
+ ```python
191
+ from authfn.types import (
192
+ InvalidCredentialsError,
193
+ ExpiredCredentialsError,
194
+ )
195
+
196
+ try:
197
+ session = await auth.provider.authenticate(request)
198
+ except InvalidCredentialsError:
199
+ # Handle invalid credentials
200
+ pass
201
+ except ExpiredCredentialsError:
202
+ # Handle expired credentials
203
+ pass
204
+ ```
205
+
206
+ ### ID Generation
207
+
208
+ **TypeScript:**
209
+ ```typescript
210
+ function generateId(prefix: string): string {
211
+ const timestamp = Date.now().toString(36);
212
+ const randomBytes = crypto.getRandomValues(new Uint8Array(5));
213
+ const random = Array.from(randomBytes)
214
+ .map(b => b.toString(36))
215
+ .join('')
216
+ .substring(0, 7);
217
+ return `${prefix}_${timestamp}${random}`;
218
+ }
219
+ ```
220
+
221
+ **Python:**
222
+ ```python
223
+ import secrets
224
+ import time
225
+
226
+ def generate_id(prefix: str) -> str:
227
+ """Generate unique ID."""
228
+ timestamp = format(int(time.time() * 1000), "x")
229
+ random_str = secrets.token_hex(5)[:7]
230
+ return f"{prefix}_{timestamp}{random_str}"
231
+ ```
232
+
233
+ ### API Key Generation
234
+
235
+ **TypeScript:**
236
+ ```typescript
237
+ function generateApiKey(prefix: string = 'ak'): string {
238
+ const randomBytes = crypto.getRandomValues(new Uint8Array(32));
239
+ const key = Array.from(randomBytes)
240
+ .map(b => b.toString(16).padStart(2, '0'))
241
+ .join('');
242
+ return `${prefix}_${key}`;
243
+ }
244
+ ```
245
+
246
+ **Python:**
247
+ ```python
248
+ import secrets
249
+
250
+ def generate_api_key(prefix: str = "ak") -> str:
251
+ """Generate a secure API key."""
252
+ random_bytes = secrets.token_bytes(32)
253
+ key = random_bytes.hex()
254
+ return f"{prefix}_{key}"
255
+ ```
256
+
257
+ ## Database Adapter Protocol
258
+
259
+ ### TypeScript Interface
260
+
261
+ ```typescript
262
+ interface Adapter {
263
+ findOne<T>(options: {
264
+ model: string;
265
+ where: WhereClause[];
266
+ namespace: string;
267
+ }): Promise<T | null>;
268
+
269
+ findMany<T>(options: {
270
+ model: string;
271
+ where: WhereClause[];
272
+ orderBy?: OrderByClause[];
273
+ namespace: string;
274
+ }): Promise<T[]>;
275
+
276
+ create(options: {
277
+ model: string;
278
+ data: Record<string, any>;
279
+ namespace: string;
280
+ }): Promise<void>;
281
+
282
+ update(options: {
283
+ model: string;
284
+ where: WhereClause[];
285
+ data: Record<string, any>;
286
+ namespace: string;
287
+ }): Promise<void>;
288
+ }
289
+ ```
290
+
291
+ ### Python Protocol
292
+
293
+ ```python
294
+ from typing import Protocol, List, Dict, Any, Optional
295
+
296
+ class DatabaseAdapter(Protocol):
297
+ """Protocol for database adapters."""
298
+
299
+ async def find_one(
300
+ self,
301
+ model: str,
302
+ where: List[WhereClause],
303
+ namespace: str,
304
+ ) -> Optional[Dict[str, Any]]:
305
+ """Find a single record."""
306
+ ...
307
+
308
+ async def find_many(
309
+ self,
310
+ model: str,
311
+ where: List[WhereClause],
312
+ order_by: Optional[List[OrderByClause]],
313
+ namespace: str,
314
+ ) -> List[Dict[str, Any]]:
315
+ """Find multiple records."""
316
+ ...
317
+
318
+ async def create(
319
+ self,
320
+ model: str,
321
+ data: Dict[str, Any],
322
+ namespace: str,
323
+ ) -> None:
324
+ """Create a new record."""
325
+ ...
326
+
327
+ async def update(
328
+ self,
329
+ model: str,
330
+ where: List[WhereClause],
331
+ data: Dict[str, Any],
332
+ namespace: str,
333
+ ) -> None:
334
+ """Update records."""
335
+ ...
336
+ ```
337
+
338
+ ## Testing
339
+
340
+ ### TypeScript
341
+ - Uses Vitest for testing
342
+ - Type-safe mocking
343
+
344
+ ### Python
345
+ - Uses pytest with pytest-asyncio
346
+ - Comprehensive test coverage
347
+ - Type-safe mocking with protocols
348
+ - Fixtures for test setup
349
+
350
+ ## Development Tools
351
+
352
+ ### TypeScript
353
+ ```json
354
+ {
355
+ "scripts": {
356
+ "build": "tsc",
357
+ "test": "vitest",
358
+ "typecheck": "tsc --noEmit"
359
+ }
360
+ }
361
+ ```
362
+
363
+ ### Python
364
+ ```toml
365
+ [project.optional-dependencies]
366
+ dev = [
367
+ "pytest>=7.4.0",
368
+ "pytest-asyncio>=0.21.0",
369
+ "mypy>=1.7.0",
370
+ "ruff>=0.1.6",
371
+ "black>=23.11.0",
372
+ ]
373
+ ```
374
+
375
+ Commands:
376
+ ```bash
377
+ pytest # Run tests
378
+ mypy authfn # Type checking
379
+ ruff check authfn # Linting
380
+ black authfn # Code formatting
381
+ ```
382
+
383
+ ## Key Differences Summary
384
+
385
+ 1. **Type System**: TypeScript uses compile-time only types; Python uses Pydantic for runtime validation
386
+ 2. **Naming Convention**: TypeScript uses camelCase; Python uses snake_case (with camelCase aliases in Pydantic)
387
+ 3. **Error Handling**: TypeScript uses try/catch with instanceof; Python uses except with exception types
388
+ 4. **Package Management**: TypeScript uses npm/package.json; Python uses pip/pyproject.toml
389
+ 5. **Module System**: TypeScript uses ES modules; Python uses standard imports
390
+ 6. **Documentation**: TypeScript uses JSDoc; Python uses docstrings
391
+ 7. **Testing**: TypeScript uses Vitest; Python uses pytest
392
+ 8. **Async Model**: Both support async/await natively, but with different underlying implementations
393
+
394
+ ## Migration Notes
395
+
396
+ If migrating from TypeScript to Python:
397
+
398
+ 1. Convert camelCase to snake_case for function/variable names
399
+ 2. Use Pydantic models instead of TypeScript interfaces
400
+ 3. Replace `null` with `None`
401
+ 4. Replace `undefined` with `None` or omit the field
402
+ 5. Use `Optional[T]` instead of `T | null`
403
+ 6. Replace `Record<string, any>` with `Dict[str, Any]`
404
+ 7. Use f-strings instead of template literals
405
+ 8. Import error classes from `authfn.types` instead of separate packages
406
+
407
+ ## Conclusion
408
+
409
+ The Python implementation maintains feature parity with the TypeScript SDK while following Python conventions and best practices. Both implementations provide:
410
+
411
+ - ✅ Type safety (compile-time in TS, compile + runtime in Python)
412
+ - ✅ Async/await support
413
+ - ✅ Database abstraction
414
+ - ✅ Comprehensive error handling
415
+ - ✅ Testing infrastructure
416
+ - ✅ Documentation and examples
417
+ - ✅ Modern tooling (linters, formatters, type checkers)