authfn 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/README.md +293 -0
  2. package/package.json +54 -0
package/README.md ADDED
@@ -0,0 +1,293 @@
1
+ # authfn
2
+
3
+ API key authentication library using Superfunctions abstractions.
4
+
5
+ ## Overview
6
+
7
+ `authfn` is a reference implementation of the `@superfunctions/auth` abstraction that provides API key-based authentication. It includes:
8
+
9
+ - **Auth Provider**: Conforms to `@superfunctions/auth` interface
10
+ - **Database Storage**: Uses `@superfunctions/db` adapters for storing API keys
11
+ - **Management API**: Optional HTTP API for managing keys (uses `@superfunctions/http`)
12
+ - **Key Generation**: Secure API key generation and validation
13
+
14
+ ## Installation
15
+
16
+ ```bash
17
+ npm install authfn @superfunctions/db @superfunctions/http
18
+ ```
19
+
20
+ ## Quick Start
21
+
22
+ ### 1. Generate Schema
23
+
24
+ First, generate the database schema for your ORM:
25
+
26
+ ```bash
27
+ npx @superfunctions/cli generate-schema \
28
+ --config ./node_modules/authfn \
29
+ --adapter drizzle \
30
+ --output ./src/db
31
+ ```
32
+
33
+ ### 2. Setup Database
34
+
35
+ ```typescript
36
+ import { drizzle } from 'drizzle-orm/postgres-js';
37
+ import postgres from 'postgres';
38
+ import * as authSchema from './db/authfn-schema';
39
+
40
+ const client = postgres(process.env.DATABASE_URL);
41
+ const db = drizzle(client, { schema: authSchema });
42
+ ```
43
+
44
+ ### 3. Create authfn Instance
45
+
46
+ ```typescript
47
+ import { createAuthFn } from 'authfn';
48
+ import { drizzleAdapter } from '@superfunctions/db/adapters';
49
+
50
+ const adapter = drizzleAdapter({ db, dialect: 'postgres' });
51
+
52
+ const auth = createAuthFn({
53
+ database: adapter,
54
+ namespace: 'authfn',
55
+ enableApi: true,
56
+ apiConfig: {
57
+ basePath: '/auth',
58
+ adminKey: process.env.ADMIN_KEY,
59
+ },
60
+ });
61
+ ```
62
+
63
+ ### 4. Use with Libraries
64
+
65
+ Use the auth provider with any library accepting `@superfunctions/auth`:
66
+
67
+ ```typescript
68
+ import { createConductBackend } from 'conduct-backend';
69
+
70
+ const conduct = createConductBackend({
71
+ database: adapter,
72
+ auth: auth.provider,
73
+ });
74
+ ```
75
+
76
+ ### 5. Mount API
77
+
78
+ Mount both the auth management API and your library's API:
79
+
80
+ ```typescript
81
+ import express from 'express';
82
+ import { toExpressRouter } from '@superfunctions/http-express';
83
+
84
+ const app = express();
85
+
86
+ // Mount auth management API
87
+ app.use('/api/auth', toExpressRouter(auth.router));
88
+
89
+ // Mount your library's API
90
+ app.use('/api/conduct', toExpressRouter(conduct.router));
91
+
92
+ app.listen(3000);
93
+ ```
94
+
95
+ ## API Reference
96
+
97
+ ### createAuthFn(config)
98
+
99
+ Creates an authfn instance.
100
+
101
+ **Config Options:**
102
+
103
+ ```typescript
104
+ {
105
+ database: Adapter; // Database adapter
106
+ namespace?: string; // Table prefix (default: 'authfn')
107
+ enableApi?: boolean; // Enable management API (default: false)
108
+ apiConfig?: {
109
+ basePath?: string; // API base path (default: '/auth')
110
+ adminKey?: string; // Admin key for managing keys
111
+ };
112
+ }
113
+ ```
114
+
115
+ **Returns:**
116
+
117
+ ```typescript
118
+ {
119
+ provider: AuthProvider; // Auth provider for use with libraries
120
+ router?: Router; // Management API router (if enabled)
121
+ createKey: Function; // Create API key programmatically
122
+ revokeKey: Function; // Revoke API key
123
+ getKey: Function; // Get API key by ID
124
+ listKeys: Function; // List API keys
125
+ }
126
+ ```
127
+
128
+ ### Management API Endpoints
129
+
130
+ When `enableApi` is true, the following endpoints are available:
131
+
132
+ #### POST /keys
133
+
134
+ Create a new API key.
135
+
136
+ **Request:**
137
+ ```json
138
+ {
139
+ "name": "My API Key",
140
+ "resourceIds": ["project_abc", "project_def"],
141
+ "scopes": ["read", "write"],
142
+ "metadata": { "team": "engineering" },
143
+ "expiresAt": "2025-12-31T23:59:59Z"
144
+ }
145
+ ```
146
+
147
+ **Response:**
148
+ ```json
149
+ {
150
+ "id": "key_abc123",
151
+ "key": "ak_64characterhexstring..."
152
+ }
153
+ ```
154
+
155
+ **Note:** The actual key value is only returned once during creation. Store it securely.
156
+
157
+ #### GET /keys
158
+
159
+ List all API keys (without key values).
160
+
161
+ **Query Parameters:**
162
+ - `resourceId` - Filter by resource ID
163
+
164
+ **Response:**
165
+ ```json
166
+ {
167
+ "keys": [
168
+ {
169
+ "id": "key_abc123",
170
+ "name": "My API Key",
171
+ "resourceIds": ["project_abc"],
172
+ "scopes": ["read", "write"],
173
+ "metadata": { "team": "engineering" },
174
+ "expiresAt": "2025-12-31T23:59:59Z",
175
+ "lastUsedAt": "2025-01-15T10:30:00Z",
176
+ "createdAt": "2025-01-01T00:00:00Z"
177
+ }
178
+ ]
179
+ }
180
+ ```
181
+
182
+ #### GET /keys/:id
183
+
184
+ Get a specific API key by ID (without key value).
185
+
186
+ #### DELETE /keys/:id
187
+
188
+ Revoke an API key.
189
+
190
+ **Response:**
191
+ ```json
192
+ {
193
+ "success": true
194
+ }
195
+ ```
196
+
197
+ ### Programmatic Usage
198
+
199
+ You can also create and manage keys programmatically:
200
+
201
+ ```typescript
202
+ // Create a key
203
+ const { id, key } = await auth.createKey({
204
+ name: 'My API Key',
205
+ resourceIds: ['project_abc'],
206
+ scopes: ['read', 'write'],
207
+ expiresAt: new Date('2025-12-31'),
208
+ });
209
+
210
+ // List keys
211
+ const keys = await auth.listKeys();
212
+
213
+ // Get a key
214
+ const apiKey = await auth.getKey('key_abc123');
215
+
216
+ // Revoke a key
217
+ await auth.revokeKey('key_abc123');
218
+ ```
219
+
220
+ ## Database Schema
221
+
222
+ authfn creates a single table:
223
+
224
+ ### `{namespace}_api_keys`
225
+
226
+ - `id` - Unique identifier
227
+ - `key` - API key value (unique, indexed)
228
+ - `name` - Descriptive name
229
+ - `resource_ids` - JSON array of resource IDs
230
+ - `scopes` - JSON array of scopes/permissions
231
+ - `metadata` - JSON object for additional data
232
+ - `expires_at` - Expiration timestamp
233
+ - `last_used_at` - Last usage timestamp
234
+ - `revoked_at` - Revocation timestamp
235
+ - `created_at` - Creation timestamp
236
+
237
+ ## Security
238
+
239
+ - API keys are 64-character hex strings with a prefix
240
+ - Keys are validated against database on each request
241
+ - Expired and revoked keys are rejected
242
+ - Management API requires admin key authentication
243
+ - Key values are never returned in list/get operations
244
+
245
+ ## Integration Examples
246
+
247
+ ### With Conduct Backend
248
+
249
+ ```typescript
250
+ const auth = createAuthFn({
251
+ database: adapter,
252
+ enableApi: true,
253
+ });
254
+
255
+ const conduct = createConductBackend({
256
+ database: adapter,
257
+ auth: {
258
+ ...auth.provider,
259
+ // Map resourceIds to projectIds
260
+ authenticate: async (request) => {
261
+ const session = await auth.provider.authenticate(request);
262
+ if (!session) return null;
263
+ return {
264
+ ...session,
265
+ projectIds: session.resourceIds,
266
+ };
267
+ },
268
+ },
269
+ });
270
+ ```
271
+
272
+ ### Custom Implementation
273
+
274
+ Implement your own auth provider using the same abstraction:
275
+
276
+ ```typescript
277
+ import type { AuthProvider, AuthSession } from '@superfunctions/auth';
278
+
279
+ const customAuth: AuthProvider = {
280
+ async authenticate(request: Request): Promise<AuthSession | null> {
281
+ // Your custom auth logic
282
+ return {
283
+ id: 'user_123',
284
+ type: 'custom',
285
+ resourceIds: ['resource_1'],
286
+ };
287
+ },
288
+ };
289
+ ```
290
+
291
+ ## License
292
+
293
+ MIT
package/package.json ADDED
@@ -0,0 +1,54 @@
1
+ {
2
+ "name": "authfn",
3
+ "version": "0.1.0",
4
+ "description": "Authentication self deployed",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "default": "./dist/index.js"
12
+ }
13
+ },
14
+ "files": [
15
+ "dist"
16
+ ],
17
+ "scripts": {
18
+ "build": "tsc",
19
+ "test": "vitest",
20
+ "test:watch": "vitest --watch",
21
+ "lint": "echo 'lint not configured'",
22
+ "typecheck": "tsc --noEmit",
23
+ "clean": "rm -rf dist"
24
+ },
25
+ "keywords": [
26
+ "auth",
27
+ "authentication",
28
+ "api-keys",
29
+ "superfunctions"
30
+ ],
31
+ "author": "21n",
32
+ "license": "MIT",
33
+ "bugs": {
34
+ "url": "https://github.com/21nCo/super-functions/issues"
35
+ },
36
+ "repository": {
37
+ "type": "git",
38
+ "url": "git+https://github.com/21nCo/super-functions.git",
39
+ "directory": "authfn"
40
+ },
41
+ "publishConfig": {
42
+ "access": "public"
43
+ },
44
+ "dependencies": {
45
+ "@superfunctions/auth": "workspace:*",
46
+ "@superfunctions/db": "workspace:*",
47
+ "@superfunctions/http": "workspace:*"
48
+ },
49
+ "devDependencies": {
50
+ "@types/node": "^22.0.0",
51
+ "typescript": "^5.6.0",
52
+ "vitest": "^3.2.4"
53
+ }
54
+ }