authfn 0.1.1 → 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.
package/README.md CHANGED
@@ -1,292 +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
- 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
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,59 +1,59 @@
1
- {
2
- "name": "authfn",
3
- "version": "0.1.1",
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": "*",
51
- "@superfunctions/db": "*",
52
- "@superfunctions/http": "*"
53
- },
54
- "devDependencies": {
55
- "@types/node": "^22.0.0",
56
- "typescript": "^5.6.0",
57
- "vitest": "^3.2.4"
58
- }
59
- }
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
+ }
package/dist/index.d.ts DELETED
@@ -1,11 +0,0 @@
1
- /**
2
- * authfn - API key authentication using Superfunctions abstractions
3
- */
4
- import type { AuthFnConfig, AuthFnInstance } from './types.js';
5
- /**
6
- * Create authfn instance
7
- */
8
- export declare function createAuthFn(config: AuthFnConfig): AuthFnInstance;
9
- export type { AuthFnConfig, AuthFnInstance, ApiKey, ApiKeySession } from './types.js';
10
- export { getSchema } from './schema.js';
11
- //# sourceMappingURL=index.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAMH,OAAO,KAAK,EAAE,YAAY,EAAE,cAAc,EAAyB,MAAM,YAAY,CAAC;AAsBtF;;GAEG;AACH,wBAAgB,YAAY,CAAC,MAAM,EAAE,YAAY,GAAG,cAAc,CA+PjE;AAGD,YAAY,EAAE,YAAY,EAAE,cAAc,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AACtF,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC"}
package/dist/index.js DELETED
@@ -1,241 +0,0 @@
1
- /**
2
- * authfn - API key authentication using Superfunctions abstractions
3
- */
4
- import { InvalidCredentialsError, ExpiredCredentialsError } from '@superfunctions/auth';
5
- import { createRouter } from '@superfunctions/http';
6
- import { UnauthorizedError, NotFoundError } from '@superfunctions/http';
7
- /**
8
- * Generate a secure API key
9
- */
10
- function generateApiKey(prefix = 'ak') {
11
- const randomBytes = crypto.getRandomValues(new Uint8Array(32));
12
- const key = Array.from(randomBytes)
13
- .map(b => b.toString(16).padStart(2, '0'))
14
- .join('');
15
- return `${prefix}_${key}`;
16
- }
17
- /**
18
- * Generate unique ID
19
- */
20
- function generateId(prefix) {
21
- const timestamp = Date.now().toString(36);
22
- const random = Math.random().toString(36).substring(2, 9);
23
- return `${prefix}_${timestamp}${random}`;
24
- }
25
- /**
26
- * Create authfn instance
27
- */
28
- export function createAuthFn(config) {
29
- const { database, namespace = 'authfn', enableApi = false, apiConfig } = config;
30
- // Auth provider implementation
31
- const provider = {
32
- async authenticate(request) {
33
- const authHeader = request.headers.get('authorization');
34
- if (!authHeader) {
35
- return null;
36
- }
37
- const token = authHeader.replace(/^Bearer\s+/i, '');
38
- if (!token) {
39
- return null;
40
- }
41
- // Look up API key in database
42
- const apiKey = await database.findOne({
43
- model: 'apiKeys',
44
- where: [
45
- { field: 'key', operator: 'eq', value: token },
46
- ],
47
- namespace,
48
- });
49
- if (!apiKey) {
50
- throw new InvalidCredentialsError('Invalid API key');
51
- }
52
- // Check if revoked
53
- if (apiKey.revokedAt) {
54
- throw new InvalidCredentialsError('API key has been revoked');
55
- }
56
- // Check if expired
57
- if (apiKey.expiresAt) {
58
- const expiresAt = new Date(apiKey.expiresAt);
59
- if (expiresAt < new Date()) {
60
- throw new ExpiredCredentialsError('API key has expired');
61
- }
62
- }
63
- // Update last used timestamp
64
- await database.update({
65
- model: 'apiKeys',
66
- where: [{ field: 'id', operator: 'eq', value: apiKey.id }],
67
- data: { lastUsedAt: new Date().toISOString() },
68
- namespace,
69
- });
70
- return {
71
- id: apiKey.id,
72
- type: 'api-key',
73
- keyId: apiKey.id,
74
- name: apiKey.name,
75
- resourceIds: apiKey.resourceIds,
76
- scopes: apiKey.scopes,
77
- expiresAt: apiKey.expiresAt ? new Date(apiKey.expiresAt) : undefined,
78
- metadata: apiKey.metadata,
79
- };
80
- },
81
- async authorize(session, resourceId) {
82
- return session.resourceIds.includes(resourceId);
83
- },
84
- async revoke(sessionId) {
85
- await database.update({
86
- model: 'apiKeys',
87
- where: [{ field: 'id', operator: 'eq', value: sessionId }],
88
- data: { revokedAt: new Date().toISOString() },
89
- namespace,
90
- });
91
- },
92
- };
93
- // Key management functions
94
- async function createKey(data) {
95
- const id = generateId('key');
96
- const key = generateApiKey('ak');
97
- await database.create({
98
- model: 'apiKeys',
99
- data: {
100
- id,
101
- key,
102
- name: data.name,
103
- resourceIds: data.resourceIds,
104
- scopes: data.scopes || null,
105
- metadata: data.metadata || null,
106
- expiresAt: data.expiresAt ? data.expiresAt.toISOString() : null,
107
- lastUsedAt: null,
108
- revokedAt: null,
109
- createdAt: new Date().toISOString(),
110
- },
111
- namespace,
112
- });
113
- return { id, key };
114
- }
115
- async function revokeKey(keyId) {
116
- await database.update({
117
- model: 'apiKeys',
118
- where: [{ field: 'id', operator: 'eq', value: keyId }],
119
- data: { revokedAt: new Date().toISOString() },
120
- namespace,
121
- });
122
- }
123
- async function getKey(keyId) {
124
- const key = await database.findOne({
125
- model: 'apiKeys',
126
- where: [{ field: 'id', operator: 'eq', value: keyId }],
127
- namespace,
128
- });
129
- return key;
130
- }
131
- async function listKeys(filters) {
132
- const where = [];
133
- if (filters?.resourceId) {
134
- where.push({ field: 'resourceIds', operator: 'contains', value: filters.resourceId });
135
- }
136
- const keys = await database.findMany({
137
- model: 'apiKeys',
138
- where,
139
- orderBy: [{ field: 'createdAt', direction: 'desc' }],
140
- namespace,
141
- });
142
- return keys;
143
- }
144
- // Create management API router if enabled
145
- let router;
146
- if (enableApi) {
147
- const adminKey = apiConfig?.adminKey;
148
- // Admin auth middleware
149
- const adminAuthMiddleware = async (req, _ctx, next) => {
150
- if (!adminKey) {
151
- return next(); // No admin key configured, skip auth
152
- }
153
- const authHeader = req.headers.get('authorization');
154
- const token = authHeader?.replace(/^Bearer\s+/i, '');
155
- if (token !== adminKey) {
156
- throw new UnauthorizedError('Invalid admin key');
157
- }
158
- return next();
159
- };
160
- router = createRouter({
161
- middleware: [adminAuthMiddleware],
162
- routes: [
163
- // POST /keys - Create API key
164
- {
165
- method: 'POST',
166
- path: '/keys',
167
- handler: async (_req, ctx) => {
168
- const body = await ctx.json();
169
- const result = await createKey({
170
- name: body.name,
171
- resourceIds: body.resourceIds,
172
- scopes: body.scopes,
173
- metadata: body.metadata,
174
- expiresAt: body.expiresAt ? new Date(body.expiresAt) : undefined,
175
- });
176
- return Response.json(result, { status: 201 });
177
- },
178
- },
179
- // GET /keys - List API keys
180
- {
181
- method: 'GET',
182
- path: '/keys',
183
- handler: async (_req, ctx) => {
184
- const resourceId = ctx.query.get('resourceId') || undefined;
185
- const keys = await listKeys({ resourceId });
186
- // Don't return the actual key values
187
- const sanitized = keys.map(k => ({
188
- id: k.id,
189
- name: k.name,
190
- resourceIds: k.resourceIds,
191
- scopes: k.scopes,
192
- metadata: k.metadata,
193
- expiresAt: k.expiresAt,
194
- lastUsedAt: k.lastUsedAt,
195
- revokedAt: k.revokedAt,
196
- createdAt: k.createdAt,
197
- }));
198
- return Response.json({ keys: sanitized });
199
- },
200
- },
201
- // GET /keys/:id - Get API key
202
- {
203
- method: 'GET',
204
- path: '/keys/:id',
205
- handler: async (_req, ctx) => {
206
- const key = await getKey(ctx.params.id);
207
- if (!key) {
208
- throw new NotFoundError('API key not found');
209
- }
210
- // Don't return the actual key value
211
- const { key: _, ...sanitized } = key;
212
- return Response.json(sanitized);
213
- },
214
- },
215
- // DELETE /keys/:id - Revoke API key
216
- {
217
- method: 'DELETE',
218
- path: '/keys/:id',
219
- handler: async (_req, ctx) => {
220
- await revokeKey(ctx.params.id);
221
- return Response.json({ success: true });
222
- },
223
- },
224
- ],
225
- });
226
- }
227
- return {
228
- provider: {
229
- authenticate: provider.authenticate.bind(provider),
230
- authorize: provider.authorize.bind(provider),
231
- revoke: provider.revoke.bind(provider),
232
- },
233
- router,
234
- createKey,
235
- revokeKey,
236
- getKey,
237
- listKeys,
238
- };
239
- }
240
- export { getSchema } from './schema.js';
241
- //# sourceMappingURL=index.js.map
package/dist/index.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAGH,OAAO,EAAE,uBAAuB,EAAE,uBAAuB,EAAE,MAAM,sBAAsB,CAAC;AACxF,OAAO,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAC;AACpD,OAAO,EAAE,iBAAiB,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAGxE;;GAEG;AACH,SAAS,cAAc,CAAC,SAAiB,IAAI;IAC3C,MAAM,WAAW,GAAG,MAAM,CAAC,eAAe,CAAC,IAAI,UAAU,CAAC,EAAE,CAAC,CAAC,CAAC;IAC/D,MAAM,GAAG,GAAG,KAAK,CAAC,IAAI,CAAC,WAAW,CAAC;SAChC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC;SACzC,IAAI,CAAC,EAAE,CAAC,CAAC;IACZ,OAAO,GAAG,MAAM,IAAI,GAAG,EAAE,CAAC;AAC5B,CAAC;AAED;;GAEG;AACH,SAAS,UAAU,CAAC,MAAc;IAChC,MAAM,SAAS,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC;IAC1C,MAAM,MAAM,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,SAAS,CAAC,CAAC,EAAE,CAAC,CA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AE,CAAC,CAAC;oBAC1C,CAAC;iBACF;aACF;SACF,CAAC,CAAC;IACL,CAAC;IAED,OAAO;QACL,QAAQ,EAAE;YACR,YAAY,EAAE,QAAQ,CAAC,YAAY,CAAC,IAAI,CAAC,QAAQ,CAAC;YAClD,SAAS,EAAE,QAAQ,CAAC,SAAU,CAAC,IAAI,CAAC,QAAQ,CAAC;YAC7C,MAAM,EAAE,QAAQ,CAAC,MAAO,CAAC,IAAI,CAAC,QAAQ,CAAC;SACxC;QACD,MAAM;QACN,SAAS;QACT,SAAS;QACT,MAAM;QACN,QAAQ;KACT,CAAC;AACJ,CAAC;AAID,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC"}
package/dist/schema.d.ts DELETED
@@ -1,12 +0,0 @@
1
- /**
2
- * Schema definition for authfn
3
- * Used by @superfunctions/cli to generate migrations
4
- */
5
- import type { TableSchema } from '@superfunctions/db';
6
- export declare function getSchema(config?: {
7
- namespace?: string;
8
- }): {
9
- version: number;
10
- schemas: TableSchema[];
11
- };
12
- //# sourceMappingURL=schema.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"schema.d.ts","sourceRoot":"","sources":["../src/schema.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AAEtD,wBAAgB,SAAS,CAAC,MAAM,CAAC,EAAE;IAAE,SAAS,CAAC,EAAE,MAAM,CAAA;CAAE,GAAG;IAC1D,OAAO,EAAE,MAAM,CAAC;IAChB,OAAO,EAAE,WAAW,EAAE,CAAC;CACxB,CAwEA"}
package/dist/schema.js DELETED
@@ -1,77 +0,0 @@
1
- /**
2
- * Schema definition for authfn
3
- * Used by @superfunctions/cli to generate migrations
4
- */
5
- export function getSchema(config) {
6
- const namespace = config?.namespace || 'authfn';
7
- return {
8
- version: 1,
9
- schemas: [
10
- // API Keys table
11
- {
12
- modelName: 'apiKeys',
13
- fields: {
14
- id: {
15
- type: 'string',
16
- required: true,
17
- fieldName: 'id',
18
- },
19
- key: {
20
- type: 'string',
21
- required: true,
22
- unique: true,
23
- fieldName: 'key',
24
- },
25
- name: {
26
- type: 'string',
27
- required: true,
28
- fieldName: 'name',
29
- },
30
- resourceIds: {
31
- type: 'json',
32
- required: true,
33
- fieldName: 'resource_ids',
34
- },
35
- scopes: {
36
- type: 'json',
37
- required: false,
38
- fieldName: 'scopes',
39
- },
40
- metadata: {
41
- type: 'json',
42
- required: false,
43
- fieldName: 'metadata',
44
- },
45
- expiresAt: {
46
- type: 'date',
47
- required: false,
48
- fieldName: 'expires_at',
49
- },
50
- lastUsedAt: {
51
- type: 'date',
52
- required: false,
53
- fieldName: 'last_used_at',
54
- },
55
- revokedAt: {
56
- type: 'date',
57
- required: false,
58
- fieldName: 'revoked_at',
59
- },
60
- createdAt: {
61
- type: 'date',
62
- required: true,
63
- fieldName: 'created_at',
64
- },
65
- },
66
- indexes: [
67
- {
68
- name: `idx_${namespace}_api_keys_key`,
69
- fields: ['key'],
70
- unique: true,
71
- },
72
- ],
73
- },
74
- ],
75
- };
76
- }
77
- //# sourceMappingURL=schema.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"schema.js","sourceRoot":"","sources":["../src/schema.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAIH,MAAM,UAAU,SAAS,CAAC,MAA+B;IAIvD,MAAM,SAAS,GAAG,MAAM,EAAE,SAAS,IAAI,QAAQ,CAAC;IAEhD,OAAO;QACL,OAAO,EAAE,CAAC;QACV,OAAO,EAAE;YACP,iBAAiB;YACjB;gBACE,SAAS,EAAE,SAAS;gBACpB,MAAM,EAAE;oBACN,EAAE,EAAE;wBACF,IAAI,EAAE,QAAQ;wBACd,QAAQ,EAAE,IAAI;wBACd,SAAS,EAAE,IAAI;qBAChB;oBACD,GAAG,EAAE;wBACH,IAAI,EAAE,QAAQ;wBACd,QAAQ,EAAE,IAAI;wBACd,MAAM,EAAE,IAAI;wBACZ,SAAS,EAAE,KAAK;qBACjB;oBACD,IAAI,EAAE;wBACJ,IAAI,EAAE,QAAQ;wBACd,QAAQ,EAAE,IAAI;wBACd,SAAS,EAAE,MAAM;qBAClB;oBACD,WAAW,EAAE;wBACX,IAAI,EAAE,MAAM;wBACZ,QAAQ,EAAE,IAAI;wBACd,SAAS,EAAE,cAAc;qBAC1B;oBACD,MAAM,EAAE;wBACN,IAAI,EAAE,MAAM;wBACZ,QAAQ,EAAE,KAAK;wBACf,SAAS,EAAE,QAAQ;qBACpB;oBACD,QAAQ,EAAE;wBACR,IAAI,EAAE,MAAM;wBACZ,QAAQ,EAAE,KAAK;wBACf,SAAS,EAAE,UAAU;qBACtB;oBACD,SAAS,EAAE;wBACT,IAAI,EAAE,MAAM;wBACZ,QAAQ,EAAE,KAAK;wBACf,SAAS,EAAE,YAAY;qBACxB;oBACD,UAAU,EAAE;wBACV,IAAI,EAAE,MAAM;wBACZ,QAAQ,EAAE,KAAK;wBACf,SAAS,EAAE,cAAc;qBAC1B;oBACD,SAAS,EAAE;wBACT,IAAI,EAAE,MAAM;wBACZ,QAAQ,EAAE,KAAK;wBACf,SAAS,EAAE,YAAY;qBACxB;oBACD,SAAS,EAAE;wBACT,IAAI,EAAE,MAAM;wBACZ,QAAQ,EAAE,IAAI;wBACd,SAAS,EAAE,YAAY;qBACxB;iBACF;gBACD,OAAO,EAAE;oBACP;wBACE,IAAI,EAAE,OAAO,SAAS,eAAe;wBACrC,MAAM,EAAE,CAAC,KAAK,CAAC;wBACf,MAAM,EAAE,IAAI;qBACb;iBACF;aACF;SACF;KACF,CAAC;AACJ,CAAC"}
package/dist/types.d.ts DELETED
@@ -1,80 +0,0 @@
1
- /**
2
- * Types for authfn
3
- */
4
- import type { AuthSession } from '@superfunctions/auth';
5
- import type { Adapter } from '@superfunctions/db';
6
- import type { Router } from '@superfunctions/http';
7
- /**
8
- * API key session extends base AuthSession
9
- */
10
- export interface ApiKeySession extends AuthSession {
11
- type: 'api-key';
12
- keyId: string;
13
- name: string;
14
- }
15
- /**
16
- * API key data stored in database
17
- */
18
- export interface ApiKey {
19
- id: string;
20
- key: string;
21
- name: string;
22
- resourceIds: string[];
23
- scopes?: string[];
24
- metadata?: Record<string, any>;
25
- expiresAt?: Date | string;
26
- lastUsedAt?: Date | string;
27
- revokedAt?: Date | string;
28
- createdAt: Date | string;
29
- }
30
- /**
31
- * Configuration for authfn
32
- */
33
- export interface AuthFnConfig {
34
- /** Database adapter */
35
- database: Adapter;
36
- /** Namespace for table prefixing (default: 'authfn') */
37
- namespace?: string;
38
- /** Mount management API (default: false) */
39
- enableApi?: boolean;
40
- /** API configuration (required if enableApi is true) */
41
- apiConfig?: {
42
- /** Base path for API routes (default: '/auth') */
43
- basePath?: string;
44
- /** Admin API key for managing keys (optional) */
45
- adminKey?: string;
46
- };
47
- }
48
- /**
49
- * AuthFn instance with provider and optional router
50
- */
51
- export interface AuthFnInstance {
52
- /** Auth provider for use with other libraries */
53
- provider: {
54
- authenticate: (request: Request) => Promise<ApiKeySession | null>;
55
- authorize: (session: ApiKeySession, resourceId: string) => Promise<boolean>;
56
- revoke: (sessionId: string) => Promise<void>;
57
- };
58
- /** Management API router (if enabled) */
59
- router?: Router;
60
- /** Create a new API key */
61
- createKey: (data: {
62
- name: string;
63
- resourceIds: string[];
64
- scopes?: string[];
65
- metadata?: Record<string, any>;
66
- expiresAt?: Date;
67
- }) => Promise<{
68
- id: string;
69
- key: string;
70
- }>;
71
- /** Revoke an API key */
72
- revokeKey: (keyId: string) => Promise<void>;
73
- /** Get API key by ID */
74
- getKey: (keyId: string) => Promise<ApiKey | null>;
75
- /** List API keys */
76
- listKeys: (filters?: {
77
- resourceId?: string;
78
- }) => Promise<ApiKey[]>;
79
- }
80
- //# sourceMappingURL=types.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAA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ClE,SAAS,EAAE,CAAC,OAAO,EAAE,aAAa,EAAE,UAAU,EAAE,MAAM,KAAK,OAAO,CAAC,OAAO,CAAC,CAAC;QAC5E,MAAM,EAAE,CAAC,SAAS,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;KAC9C,CAAC;IAEF,yCAAyC;IACzC,MAAM,CAAC,EAAE,MAAM,CAAC;IAEhB,2BAA2B;IAC3B,SAAS,EAAE,CAAC,IAAI,EAAE;QAChB,IAAI,EAAE,MAAM,CAAC;QACb,WAAW,EAAE,MAAM,EAAE,CAAC;QACtB,MAAM,CAAC,EAAE,MAAM,EAAE,CAAC;QAClB,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;QAC/B,SAAS,CAAC,EAAE,IAAI,CAAC;KAClB,KAAK,OAAO,CAAC;QAAE,EAAE,EAAE,MAAM,CAAC;QAAC,GAAG,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IAE3C,wBAAwB;IACxB,SAAS,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IAE5C,wBAAwB;IACxB,MAAM,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAAC;IAElD,oBAAoB;IACpB,QAAQ,EAAE,CAAC,OAAO,CAAC,EAAE;QAAE,UAAU,CAAC,EAAE,MAAM,CAAA;KAAE,KAAK,OAAO,CAAC,MAAM,EAAE,CAAC,CAAC;CACpE"}
package/dist/types.js DELETED
@@ -1,5 +0,0 @@
1
- /**
2
- * Types for authfn
3
- */
4
- export {};
5
- //# sourceMappingURL=types.js.map
package/dist/types.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;GAEG"}