authfn 0.1.0 → 0.1.2

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 +292 -293
  2. package/package.json +59 -54
package/README.md CHANGED
@@ -1,293 +1,292 @@
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
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
+ adminKey: process.env.ADMIN_KEY, // Optional: protect management API
58
+ },
59
+ });
60
+ ```
61
+
62
+ ### 4. Use with Libraries
63
+
64
+ Use the auth provider with any library accepting `@superfunctions/auth`:
65
+
66
+ ```typescript
67
+ import { createConductBackend } from 'conduct-backend';
68
+
69
+ const conduct = createConductBackend({
70
+ database: adapter,
71
+ auth: auth.provider,
72
+ });
73
+ ```
74
+
75
+ ### 5. Mount API
76
+
77
+ Mount both the auth management API and your library's API:
78
+
79
+ ```typescript
80
+ import express from 'express';
81
+ import { toExpress } from '@superfunctions/http-express';
82
+
83
+ const app = express();
84
+
85
+ // Mount auth management API
86
+ app.use('/api/auth', toExpress(auth.router));
87
+
88
+ // Mount your library's API
89
+ app.use('/api/conduct', toExpress(conduct.router));
90
+
91
+ app.listen(3000);
92
+ ```
93
+
94
+ ## API Reference
95
+
96
+ ### createAuthFn(config)
97
+
98
+ Creates an authfn instance.
99
+
100
+ **Config Options:**
101
+
102
+ ```typescript
103
+ {
104
+ database: Adapter; // Database adapter
105
+ namespace?: string; // Table prefix (default: 'authfn')
106
+ enableApi?: boolean; // Enable management API (default: false)
107
+ apiConfig?: {
108
+ basePath?: string; // API base path (default: '/auth')
109
+ adminKey?: string; // Admin key for managing keys
110
+ };
111
+ }
112
+ ```
113
+
114
+ **Returns:**
115
+
116
+ ```typescript
117
+ {
118
+ provider: AuthProvider; // Auth provider for use with libraries
119
+ router?: Router; // Management API router (if enabled)
120
+ createKey: Function; // Create API key programmatically
121
+ revokeKey: Function; // Revoke API key
122
+ getKey: Function; // Get API key by ID
123
+ listKeys: Function; // List API keys
124
+ }
125
+ ```
126
+
127
+ ### Management API Endpoints
128
+
129
+ When `enableApi` is true, the following endpoints are available:
130
+
131
+ #### POST /keys
132
+
133
+ Create a new API key.
134
+
135
+ **Request:**
136
+ ```json
137
+ {
138
+ "name": "My API Key",
139
+ "resourceIds": ["project_abc", "project_def"],
140
+ "scopes": ["read", "write"],
141
+ "metadata": { "team": "engineering" },
142
+ "expiresAt": "2025-12-31T23:59:59Z"
143
+ }
144
+ ```
145
+
146
+ **Response:**
147
+ ```json
148
+ {
149
+ "id": "key_abc123",
150
+ "key": "ak_64characterhexstring..."
151
+ }
152
+ ```
153
+
154
+ **Note:** The actual key value is only returned once during creation. Store it securely.
155
+
156
+ #### GET /keys
157
+
158
+ List all API keys (without key values).
159
+
160
+ **Query Parameters:**
161
+ - `resourceId` - Filter by resource ID
162
+
163
+ **Response:**
164
+ ```json
165
+ {
166
+ "keys": [
167
+ {
168
+ "id": "key_abc123",
169
+ "name": "My API Key",
170
+ "resourceIds": ["project_abc"],
171
+ "scopes": ["read", "write"],
172
+ "metadata": { "team": "engineering" },
173
+ "expiresAt": "2025-12-31T23:59:59Z",
174
+ "lastUsedAt": "2025-01-15T10:30:00Z",
175
+ "createdAt": "2025-01-01T00:00:00Z"
176
+ }
177
+ ]
178
+ }
179
+ ```
180
+
181
+ #### GET /keys/:id
182
+
183
+ Get a specific API key by ID (without key value).
184
+
185
+ #### DELETE /keys/:id
186
+
187
+ Revoke an API key.
188
+
189
+ **Response:**
190
+ ```json
191
+ {
192
+ "success": true
193
+ }
194
+ ```
195
+
196
+ ### Programmatic Usage
197
+
198
+ You can also create and manage keys programmatically:
199
+
200
+ ```typescript
201
+ // Create a key
202
+ const { id, key } = await auth.createKey({
203
+ name: 'My API Key',
204
+ resourceIds: ['project_abc'],
205
+ scopes: ['read', 'write'],
206
+ expiresAt: new Date('2025-12-31'),
207
+ });
208
+
209
+ // List keys
210
+ const keys = await auth.listKeys();
211
+
212
+ // Get a key
213
+ const apiKey = await auth.getKey('key_abc123');
214
+
215
+ // Revoke a key
216
+ await auth.revokeKey('key_abc123');
217
+ ```
218
+
219
+ ## Database Schema
220
+
221
+ authfn creates a single table:
222
+
223
+ ### `{namespace}_api_keys`
224
+
225
+ - `id` - Unique identifier
226
+ - `key` - API key value (unique, indexed)
227
+ - `name` - Descriptive name
228
+ - `resource_ids` - JSON array of resource IDs
229
+ - `scopes` - JSON array of scopes/permissions
230
+ - `metadata` - JSON object for additional data
231
+ - `expires_at` - Expiration timestamp
232
+ - `last_used_at` - Last usage timestamp
233
+ - `revoked_at` - Revocation timestamp
234
+ - `created_at` - Creation timestamp
235
+
236
+ ## Security
237
+
238
+ - API keys are 64-character hex strings with a prefix
239
+ - Keys are validated against database on each request
240
+ - Expired and revoked keys are rejected
241
+ - Management API requires admin key authentication
242
+ - Key values are never returned in list/get operations
243
+
244
+ ## Integration Examples
245
+
246
+ ### With Conduct Backend
247
+
248
+ ```typescript
249
+ const auth = createAuthFn({
250
+ database: adapter,
251
+ enableApi: true,
252
+ });
253
+
254
+ const conduct = createConductBackend({
255
+ database: adapter,
256
+ auth: {
257
+ ...auth.provider,
258
+ // Map resourceIds to projectIds
259
+ authenticate: async (request) => {
260
+ const session = await auth.provider.authenticate(request);
261
+ if (!session) return null;
262
+ return {
263
+ ...session,
264
+ projectIds: session.resourceIds,
265
+ };
266
+ },
267
+ },
268
+ });
269
+ ```
270
+
271
+ ### Custom Implementation
272
+
273
+ Implement your own auth provider using the same abstraction:
274
+
275
+ ```typescript
276
+ import type { AuthProvider, AuthSession } from '@superfunctions/auth';
277
+
278
+ const customAuth: AuthProvider = {
279
+ async authenticate(request: Request): Promise<AuthSession | null> {
280
+ // Your custom auth logic
281
+ return {
282
+ id: 'user_123',
283
+ type: 'custom',
284
+ resourceIds: ['resource_1'],
285
+ };
286
+ },
287
+ };
288
+ ```
289
+
290
+ ## License
291
+
292
+ MIT
package/package.json CHANGED
@@ -1,54 +1,59 @@
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
- }
1
+ {
2
+ "name": "authfn",
3
+ "version": "0.1.2",
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
+ "superfunctions": {
45
+ "initFunction": "createAuthFn",
46
+ "schemaVersion": 1,
47
+ "namespace": "authfn"
48
+ },
49
+ "dependencies": {
50
+ "@superfunctions/auth": "0.1.1",
51
+ "@superfunctions/db": "0.1.3",
52
+ "@superfunctions/http": "0.1.2"
53
+ },
54
+ "devDependencies": {
55
+ "@types/node": "^22.0.0",
56
+ "typescript": "^5.6.0",
57
+ "vitest": "^3.2.4"
58
+ }
59
+ }