@solvapay/auth 1.0.8-preview.6 → 1.0.8-preview.7

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,159 @@
1
+ /**
2
+ * Next.js Route Utilities
3
+ *
4
+ * Helper functions for common patterns in Next.js API routes.
5
+ * These utilities work with authenticated requests where user IDs
6
+ * have been extracted and set in headers (e.g., by middleware).
7
+ *
8
+ * Note: These functions work with the standard web Request API
9
+ * and can be used with Next.js NextRequest (which extends Request)
10
+ */
11
+ /**
12
+ * Extract user ID from request headers.
13
+ *
14
+ * Checks for the 'x-user-id' header which is commonly set by authentication
15
+ * middleware after successful authentication. This header is typically set
16
+ * by Next.js middleware that validates JWT tokens or session cookies.
17
+ *
18
+ * @param request - Request object (works with NextRequest from next/server)
19
+ * @param options - Configuration options
20
+ * @param options.headerName - Custom header name (default: 'x-user-id')
21
+ * @returns User ID string or null if not found
22
+ *
23
+ * @example
24
+ * ```typescript
25
+ * import { NextRequest, NextResponse } from 'next/server';
26
+ * import { getUserIdFromRequest } from '@solvapay/auth';
27
+ *
28
+ * export async function GET(request: NextRequest) {
29
+ * const userId = getUserIdFromRequest(request);
30
+ *
31
+ * if (!userId) {
32
+ * return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
33
+ * }
34
+ *
35
+ * // Use userId...
36
+ * return NextResponse.json({ userId });
37
+ * }
38
+ * ```
39
+ *
40
+ * @see {@link requireUserId} for a version that returns an error response
41
+ * @since 1.0.0
42
+ */
43
+ export declare function getUserIdFromRequest(request: Request, options?: {
44
+ headerName?: string;
45
+ }): string | null;
46
+ /**
47
+ * Extract user email from Supabase JWT token in Authorization header.
48
+ *
49
+ * Parses and validates a Supabase JWT token from the Authorization header
50
+ * and extracts the email claim. Returns null if the token is missing, invalid,
51
+ * or expired.
52
+ *
53
+ * Uses dynamic imports for Edge runtime compatibility.
54
+ *
55
+ * @param request - Request object (works with NextRequest from next/server)
56
+ * @param options - Configuration options
57
+ * @param options.jwtSecret - Supabase JWT secret (defaults to SUPABASE_JWT_SECRET env var)
58
+ * @returns User email string or null if not found
59
+ *
60
+ * @example
61
+ * ```typescript
62
+ * import { NextRequest, NextResponse } from 'next/server';
63
+ * import { getUserEmailFromRequest } from '@solvapay/auth';
64
+ *
65
+ * export async function GET(request: NextRequest) {
66
+ * const email = await getUserEmailFromRequest(request);
67
+ *
68
+ * if (!email) {
69
+ * return NextResponse.json({ error: 'Email not found' }, { status: 401 });
70
+ * }
71
+ *
72
+ * return NextResponse.json({ email });
73
+ * }
74
+ * ```
75
+ *
76
+ * @see {@link getUserNameFromRequest} for extracting user name
77
+ * @since 1.0.0
78
+ */
79
+ export declare function getUserEmailFromRequest(request: Request, options?: {
80
+ jwtSecret?: string;
81
+ }): Promise<string | null>;
82
+ /**
83
+ * Extract user name from Supabase JWT token in Authorization header.
84
+ *
85
+ * Parses and validates a Supabase JWT token from the Authorization header
86
+ * and extracts the name from user metadata. Checks multiple possible locations:
87
+ * - `user_metadata.full_name`
88
+ * - `user_metadata.name`
89
+ * - `name` claim
90
+ *
91
+ * Returns null if the token is missing, invalid, or name is not found.
92
+ *
93
+ * @param request - Request object (works with NextRequest from next/server)
94
+ * @param options - Configuration options
95
+ * @param options.jwtSecret - Supabase JWT secret (defaults to SUPABASE_JWT_SECRET env var)
96
+ * @returns User name string or null if not found
97
+ *
98
+ * @example
99
+ * ```typescript
100
+ * import { NextRequest, NextResponse } from 'next/server';
101
+ * import { getUserNameFromRequest } from '@solvapay/auth';
102
+ *
103
+ * export async function GET(request: NextRequest) {
104
+ * const name = await getUserNameFromRequest(request);
105
+ *
106
+ * return NextResponse.json({ name: name || 'Guest' });
107
+ * }
108
+ * ```
109
+ *
110
+ * @see {@link getUserEmailFromRequest} for extracting user email
111
+ * @since 1.0.0
112
+ */
113
+ export declare function getUserNameFromRequest(request: Request, options?: {
114
+ jwtSecret?: string;
115
+ }): Promise<string | null>;
116
+ /**
117
+ * Require user ID from request headers or return an error response.
118
+ *
119
+ * This is a convenience function that combines `getUserIdFromRequest()` with
120
+ * error handling. If the user ID is not found, it returns a Response object
121
+ * with a 401 status that can be directly returned from Next.js route handlers.
122
+ *
123
+ * Returns a standard Response object that works with Next.js (NextResponse
124
+ * extends Response, so this is fully compatible).
125
+ *
126
+ * @param request - Request object (works with NextRequest from next/server)
127
+ * @param options - Configuration options
128
+ * @param options.headerName - Custom header name (default: 'x-user-id')
129
+ * @param options.errorMessage - Custom error message (default: 'Unauthorized')
130
+ * @param options.errorDetails - Custom error details (default: 'User ID not found. Ensure middleware is configured.')
131
+ * @returns Either the user ID string or a Response error object with 401 status
132
+ *
133
+ * @example
134
+ * ```typescript
135
+ * import { NextRequest, NextResponse } from 'next/server';
136
+ * import { requireUserId } from '@solvapay/auth';
137
+ *
138
+ * export async function GET(request: NextRequest) {
139
+ * const userIdOrError = requireUserId(request);
140
+ *
141
+ * if (userIdOrError instanceof Response) {
142
+ * return userIdOrError; // Returns 401 error
143
+ * }
144
+ *
145
+ * // userIdOrError is now a string
146
+ * const userId = userIdOrError;
147
+ * // Use userId...
148
+ * }
149
+ * ```
150
+ *
151
+ * @see {@link getUserIdFromRequest} for a version that returns null instead of error
152
+ * @since 1.0.0
153
+ */
154
+ export declare function requireUserId(request: Request, options?: {
155
+ headerName?: string;
156
+ errorMessage?: string;
157
+ errorDetails?: string;
158
+ }): string | Response;
159
+ //# sourceMappingURL=next-utils.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"next-utils.d.ts","sourceRoot":"","sources":["../../src/next-utils.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AACH,wBAAgB,oBAAoB,CAClC,OAAO,EAAE,OAAO,EAChB,OAAO,CAAC,EAAE;IACR,UAAU,CAAC,EAAE,MAAM,CAAA;CACpB,GACA,MAAM,GAAG,IAAI,CAGf;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AACH,wBAAsB,uBAAuB,CAC3C,OAAO,EAAE,OAAO,EAChB,OAAO,CAAC,EAAE;IACR,SAAS,CAAC,EAAE,MAAM,CAAA;CACnB,GACA,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAgCxB;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AACH,wBAAsB,sBAAsB,CAC1C,OAAO,EAAE,OAAO,EAChB,OAAO,CAAC,EAAE;IACR,SAAS,CAAC,EAAE,MAAM,CAAA;CACnB,GACA,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAqCxB;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqCG;AACH,wBAAgB,aAAa,CAC3B,OAAO,EAAE,OAAO,EAChB,OAAO,CAAC,EAAE;IACR,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,YAAY,CAAC,EAAE,MAAM,CAAA;IACrB,YAAY,CAAC,EAAE,MAAM,CAAA;CACtB,GACA,MAAM,GAAG,QAAQ,CAgBnB"}
@@ -0,0 +1,222 @@
1
+ /**
2
+ * Next.js Route Utilities
3
+ *
4
+ * Helper functions for common patterns in Next.js API routes.
5
+ * These utilities work with authenticated requests where user IDs
6
+ * have been extracted and set in headers (e.g., by middleware).
7
+ *
8
+ * Note: These functions work with the standard web Request API
9
+ * and can be used with Next.js NextRequest (which extends Request)
10
+ */
11
+ /**
12
+ * Extract user ID from request headers.
13
+ *
14
+ * Checks for the 'x-user-id' header which is commonly set by authentication
15
+ * middleware after successful authentication. This header is typically set
16
+ * by Next.js middleware that validates JWT tokens or session cookies.
17
+ *
18
+ * @param request - Request object (works with NextRequest from next/server)
19
+ * @param options - Configuration options
20
+ * @param options.headerName - Custom header name (default: 'x-user-id')
21
+ * @returns User ID string or null if not found
22
+ *
23
+ * @example
24
+ * ```typescript
25
+ * import { NextRequest, NextResponse } from 'next/server';
26
+ * import { getUserIdFromRequest } from '@solvapay/auth';
27
+ *
28
+ * export async function GET(request: NextRequest) {
29
+ * const userId = getUserIdFromRequest(request);
30
+ *
31
+ * if (!userId) {
32
+ * return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
33
+ * }
34
+ *
35
+ * // Use userId...
36
+ * return NextResponse.json({ userId });
37
+ * }
38
+ * ```
39
+ *
40
+ * @see {@link requireUserId} for a version that returns an error response
41
+ * @since 1.0.0
42
+ */
43
+ export function getUserIdFromRequest(request, options) {
44
+ const headerName = options?.headerName || 'x-user-id';
45
+ return request.headers.get(headerName);
46
+ }
47
+ /**
48
+ * Extract user email from Supabase JWT token in Authorization header.
49
+ *
50
+ * Parses and validates a Supabase JWT token from the Authorization header
51
+ * and extracts the email claim. Returns null if the token is missing, invalid,
52
+ * or expired.
53
+ *
54
+ * Uses dynamic imports for Edge runtime compatibility.
55
+ *
56
+ * @param request - Request object (works with NextRequest from next/server)
57
+ * @param options - Configuration options
58
+ * @param options.jwtSecret - Supabase JWT secret (defaults to SUPABASE_JWT_SECRET env var)
59
+ * @returns User email string or null if not found
60
+ *
61
+ * @example
62
+ * ```typescript
63
+ * import { NextRequest, NextResponse } from 'next/server';
64
+ * import { getUserEmailFromRequest } from '@solvapay/auth';
65
+ *
66
+ * export async function GET(request: NextRequest) {
67
+ * const email = await getUserEmailFromRequest(request);
68
+ *
69
+ * if (!email) {
70
+ * return NextResponse.json({ error: 'Email not found' }, { status: 401 });
71
+ * }
72
+ *
73
+ * return NextResponse.json({ email });
74
+ * }
75
+ * ```
76
+ *
77
+ * @see {@link getUserNameFromRequest} for extracting user name
78
+ * @since 1.0.0
79
+ */
80
+ export async function getUserEmailFromRequest(request, options) {
81
+ const authHeader = request.headers.get('authorization');
82
+ if (!authHeader || !authHeader.startsWith('Bearer ')) {
83
+ return null;
84
+ }
85
+ const token = authHeader.slice(7);
86
+ if (!token) {
87
+ return null;
88
+ }
89
+ try {
90
+ // Dynamic import to avoid requiring jose if not used (Edge-compatible)
91
+ const { jwtVerify } = await import('jose');
92
+ const jwtSecret = options?.jwtSecret || process.env.SUPABASE_JWT_SECRET;
93
+ if (!jwtSecret) {
94
+ return null;
95
+ }
96
+ const secret = new TextEncoder().encode(jwtSecret);
97
+ const { payload } = await jwtVerify(token, secret, {
98
+ algorithms: ['HS256'],
99
+ });
100
+ // Extract email from payload (Supabase stores email in 'email' claim)
101
+ return payload.email ? String(payload.email) : null;
102
+ }
103
+ catch {
104
+ // Return null on any error (invalid token, expired, etc.)
105
+ return null;
106
+ }
107
+ }
108
+ /**
109
+ * Extract user name from Supabase JWT token in Authorization header.
110
+ *
111
+ * Parses and validates a Supabase JWT token from the Authorization header
112
+ * and extracts the name from user metadata. Checks multiple possible locations:
113
+ * - `user_metadata.full_name`
114
+ * - `user_metadata.name`
115
+ * - `name` claim
116
+ *
117
+ * Returns null if the token is missing, invalid, or name is not found.
118
+ *
119
+ * @param request - Request object (works with NextRequest from next/server)
120
+ * @param options - Configuration options
121
+ * @param options.jwtSecret - Supabase JWT secret (defaults to SUPABASE_JWT_SECRET env var)
122
+ * @returns User name string or null if not found
123
+ *
124
+ * @example
125
+ * ```typescript
126
+ * import { NextRequest, NextResponse } from 'next/server';
127
+ * import { getUserNameFromRequest } from '@solvapay/auth';
128
+ *
129
+ * export async function GET(request: NextRequest) {
130
+ * const name = await getUserNameFromRequest(request);
131
+ *
132
+ * return NextResponse.json({ name: name || 'Guest' });
133
+ * }
134
+ * ```
135
+ *
136
+ * @see {@link getUserEmailFromRequest} for extracting user email
137
+ * @since 1.0.0
138
+ */
139
+ export async function getUserNameFromRequest(request, options) {
140
+ const authHeader = request.headers.get('authorization');
141
+ if (!authHeader || !authHeader.startsWith('Bearer ')) {
142
+ return null;
143
+ }
144
+ const token = authHeader.slice(7);
145
+ if (!token) {
146
+ return null;
147
+ }
148
+ try {
149
+ // Dynamic import to avoid requiring jose if not used (Edge-compatible)
150
+ const { jwtVerify } = await import('jose');
151
+ const jwtSecret = options?.jwtSecret || process.env.SUPABASE_JWT_SECRET;
152
+ if (!jwtSecret) {
153
+ return null;
154
+ }
155
+ const secret = new TextEncoder().encode(jwtSecret);
156
+ const { payload } = await jwtVerify(token, secret, {
157
+ algorithms: ['HS256'],
158
+ });
159
+ // Extract name from payload (Supabase stores name in 'user_metadata.full_name' or 'user_metadata.name' or 'name' claim)
160
+ const name = payload.user_metadata?.full_name ||
161
+ payload.user_metadata?.name ||
162
+ payload.name ||
163
+ null;
164
+ return name ? String(name) : null;
165
+ }
166
+ catch {
167
+ // Return null on any error (invalid token, expired, etc.)
168
+ return null;
169
+ }
170
+ }
171
+ /**
172
+ * Require user ID from request headers or return an error response.
173
+ *
174
+ * This is a convenience function that combines `getUserIdFromRequest()` with
175
+ * error handling. If the user ID is not found, it returns a Response object
176
+ * with a 401 status that can be directly returned from Next.js route handlers.
177
+ *
178
+ * Returns a standard Response object that works with Next.js (NextResponse
179
+ * extends Response, so this is fully compatible).
180
+ *
181
+ * @param request - Request object (works with NextRequest from next/server)
182
+ * @param options - Configuration options
183
+ * @param options.headerName - Custom header name (default: 'x-user-id')
184
+ * @param options.errorMessage - Custom error message (default: 'Unauthorized')
185
+ * @param options.errorDetails - Custom error details (default: 'User ID not found. Ensure middleware is configured.')
186
+ * @returns Either the user ID string or a Response error object with 401 status
187
+ *
188
+ * @example
189
+ * ```typescript
190
+ * import { NextRequest, NextResponse } from 'next/server';
191
+ * import { requireUserId } from '@solvapay/auth';
192
+ *
193
+ * export async function GET(request: NextRequest) {
194
+ * const userIdOrError = requireUserId(request);
195
+ *
196
+ * if (userIdOrError instanceof Response) {
197
+ * return userIdOrError; // Returns 401 error
198
+ * }
199
+ *
200
+ * // userIdOrError is now a string
201
+ * const userId = userIdOrError;
202
+ * // Use userId...
203
+ * }
204
+ * ```
205
+ *
206
+ * @see {@link getUserIdFromRequest} for a version that returns null instead of error
207
+ * @since 1.0.0
208
+ */
209
+ export function requireUserId(request, options) {
210
+ const headerName = options?.headerName || 'x-user-id';
211
+ const errorMessage = options?.errorMessage || 'Unauthorized';
212
+ const errorDetails = options?.errorDetails || 'User ID not found. Ensure middleware is configured.';
213
+ const userId = request.headers.get(headerName);
214
+ if (!userId) {
215
+ return new Response(JSON.stringify({ error: errorMessage, details: errorDetails }), {
216
+ status: 401,
217
+ headers: { 'Content-Type': 'application/json' },
218
+ });
219
+ }
220
+ return userId;
221
+ }
222
+ //# sourceMappingURL=next-utils.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"next-utils.js","sourceRoot":"","sources":["../../src/next-utils.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AACH,MAAM,UAAU,oBAAoB,CAClC,OAAgB,EAChB,OAEC;IAED,MAAM,UAAU,GAAG,OAAO,EAAE,UAAU,IAAI,WAAW,CAAA;IACrD,OAAO,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,UAAU,CAAC,CAAA;AACxC,CAAC;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AACH,MAAM,CAAC,KAAK,UAAU,uBAAuB,CAC3C,OAAgB,EAChB,OAEC;IAED,MAAM,UAAU,GAAG,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,eAAe,CAAC,CAAA;IAEvD,IAAI,CAAC,UAAU,IAAI,CAAC,UAAU,CAAC,UAAU,CAAC,SAAS,CAAC,EAAE,CAAC;QACrD,OAAO,IAAI,CAAA;IACb,CAAC;IAED,MAAM,KAAK,GAAG,UAAU,CAAC,KAAK,CAAC,CAAC,CAAC,CAAA;IACjC,IAAI,CAAC,KAAK,EAAE,CAAC;QACX,OAAO,IAAI,CAAA;IACb,CAAC;IAED,IAAI,CAAC;QACH,uEAAuE;QACvE,MAAM,EAAE,SAAS,EAAE,GAAG,MAAM,MAAM,CAAC,MAAM,CAAC,CAAA;QAE1C,MAAM,SAAS,GAAG,OAAO,EAAE,SAAS,IAAI,OAAO,CAAC,GAAG,CAAC,mBAAmB,CAAA;QACvE,IAAI,CAAC,SAAS,EAAE,CAAC;YAC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+ * Suitable for validating opaque tokens issued by SolvaPay's hosted OAuth service.
6
+ */
7
+ import type { AuthAdapter, RequestLike } from './adapter';
8
+ export interface SolvapayAuthAdapterConfig {
9
+ /**
10
+ * SolvaPay API Base URL (e.g. https://api.solvapay.com)
11
+ */
12
+ apiBaseUrl: string;
13
+ }
14
+ /**
15
+ * SolvaPay authentication adapter
16
+ *
17
+ * Validates tokens by calling the SolvaPay userinfo endpoint.
18
+ * This is required for opaque tokens which cannot be verified offline.
19
+ */
20
+ export declare class SolvapayAuthAdapter implements AuthAdapter {
21
+ private apiBaseUrl;
22
+ constructor(config: SolvapayAuthAdapterConfig);
23
+ getUserIdFromRequest(req: Request | RequestLike): Promise<string | null>;
24
+ }
25
+ /**
26
+ * SolvaPay OAuth Client Helpers
27
+ */
28
+ export interface SolvapayOAuthConfig {
29
+ clientId: string;
30
+ clientSecret?: string;
31
+ authUrl: string;
32
+ tokenUrl: string;
33
+ redirectUri: string;
34
+ }
35
+ export interface TokenResponse {
36
+ access_token: string;
37
+ token_type: string;
38
+ expires_in: number;
39
+ refresh_token?: string;
40
+ scope?: string;
41
+ }
42
+ export declare class SolvapayOAuthClient {
43
+ private config;
44
+ constructor(config: SolvapayOAuthConfig);
45
+ /**
46
+ * Get the URL to redirect the user to for login
47
+ */
48
+ getAuthorizationUrl(options?: {
49
+ state?: string;
50
+ scope?: string;
51
+ }): string;
52
+ /**
53
+ * Exchange an authorization code for an access token
54
+ */
55
+ exchangeCodeForToken(code: string): Promise<TokenResponse>;
56
+ /**
57
+ * Revoke a token (Sign Out)
58
+ */
59
+ revokeToken(token: string): Promise<void>;
60
+ /**
61
+ * Get user info using access token
62
+ */
63
+ getUserInfo(accessToken: string, userInfoUrl?: string): Promise<Record<string, unknown>>;
64
+ }
65
+ //# sourceMappingURL=solvapay.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"solvapay.d.ts","sourceRoot":"","sources":["../../src/solvapay.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;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EAAE,OAAO,CAAC,CAAC;CAqB/F"}
@@ -0,0 +1,143 @@
1
+ /**
2
+ * SolvaPay Auth Adapter
3
+ *
4
+ * Validates SolvaPay OAuth tokens by calling the userinfo endpoint.
5
+ * Suitable for validating opaque tokens issued by SolvaPay's hosted OAuth service.
6
+ */
7
+ /**
8
+ * SolvaPay authentication adapter
9
+ *
10
+ * Validates tokens by calling the SolvaPay userinfo endpoint.
11
+ * This is required for opaque tokens which cannot be verified offline.
12
+ */
13
+ export class SolvapayAuthAdapter {
14
+ apiBaseUrl;
15
+ constructor(config) {
16
+ this.apiBaseUrl = config.apiBaseUrl.replace(/\/$/, '');
17
+ }
18
+ async getUserIdFromRequest(req) {
19
+ try {
20
+ const headers = 'headers' in req ? req.headers : req;
21
+ const authHeader = headers.get('authorization');
22
+ if (!authHeader || !authHeader.startsWith('Bearer ')) {
23
+ return null;
24
+ }
25
+ const token = authHeader.slice(7);
26
+ if (!token) {
27
+ return null;
28
+ }
29
+ // Call SolvaPay userinfo endpoint to validate token and get user ID
30
+ const response = await fetch(`${this.apiBaseUrl}/v1/customer/auth/userinfo`, {
31
+ method: 'GET',
32
+ headers: {
33
+ Authorization: `Bearer ${token}`,
34
+ 'Content-Type': 'application/json',
35
+ },
36
+ });
37
+ if (!response.ok) {
38
+ return null;
39
+ }
40
+ const userInfo = await response.json();
41
+ // Return subject (User ID) or customer reference
42
+ return userInfo.sub || userInfo.id || userInfo.customerRef || null;
43
+ }
44
+ catch {
45
+ return null;
46
+ }
47
+ }
48
+ }
49
+ export class SolvapayOAuthClient {
50
+ config;
51
+ constructor(config) {
52
+ this.config = config;
53
+ }
54
+ /**
55
+ * Get the URL to redirect the user to for login
56
+ */
57
+ getAuthorizationUrl(options = {}) {
58
+ const params = new URLSearchParams({
59
+ response_type: 'code',
60
+ client_id: this.config.clientId,
61
+ redirect_uri: this.config.redirectUri,
62
+ });
63
+ if (options.state)
64
+ params.append('state', options.state);
65
+ if (options.scope)
66
+ params.append('scope', options.scope);
67
+ return `${this.config.authUrl}?${params.toString()}`;
68
+ }
69
+ /**
70
+ * Exchange an authorization code for an access token
71
+ */
72
+ async exchangeCodeForToken(code) {
73
+ const body = new URLSearchParams({
74
+ grant_type: 'authorization_code',
75
+ code,
76
+ client_id: this.config.clientId,
77
+ redirect_uri: this.config.redirectUri,
78
+ });
79
+ if (this.config.clientSecret) {
80
+ body.append('client_secret', this.config.clientSecret);
81
+ }
82
+ const response = await fetch(this.config.tokenUrl, {
83
+ method: 'POST',
84
+ headers: {
85
+ 'Content-Type': 'application/x-www-form-urlencoded',
86
+ Accept: 'application/json',
87
+ },
88
+ body: body.toString(),
89
+ });
90
+ if (!response.ok) {
91
+ const text = await response.text();
92
+ throw new Error(`Failed to exchange code: ${response.status} ${text}`);
93
+ }
94
+ return response.json();
95
+ }
96
+ /**
97
+ * Revoke a token (Sign Out)
98
+ */
99
+ async revokeToken(token) {
100
+ // Note: Standard RFC7009 revocation endpoint is usually /oauth/revoke
101
+ // Assuming SolvaPay follows this or uses a specific endpoint.
102
+ // Constructing revocation URL based on tokenUrl pattern if not explicitly provided,
103
+ // or using a known path relative to apiBaseUrl if available.
104
+ // For now, assuming it's near the token endpoint.
105
+ const revokeUrl = this.config.tokenUrl.replace('/token', '/revoke');
106
+ const body = new URLSearchParams({
107
+ token,
108
+ client_id: this.config.clientId,
109
+ });
110
+ if (this.config.clientSecret) {
111
+ body.append('client_secret', this.config.clientSecret);
112
+ }
113
+ await fetch(revokeUrl, {
114
+ method: 'POST',
115
+ headers: {
116
+ 'Content-Type': 'application/x-www-form-urlencoded',
117
+ },
118
+ body: body.toString(),
119
+ });
120
+ }
121
+ /**
122
+ * Get user info using access token
123
+ */
124
+ async getUserInfo(accessToken, userInfoUrl) {
125
+ // If userInfoUrl is not provided, try to guess from tokenUrl or config
126
+ // But typically this client is used alongside the adapter which knows the base URL
127
+ if (!userInfoUrl) {
128
+ throw new Error('userInfoUrl is required');
129
+ }
130
+ const response = await fetch(userInfoUrl, {
131
+ method: 'GET',
132
+ headers: {
133
+ Authorization: `Bearer ${accessToken}`,
134
+ Accept: 'application/json',
135
+ },
136
+ });
137
+ if (!response.ok) {
138
+ throw new Error(`Failed to fetch user info: ${response.status}`);
139
+ }
140
+ return response.json();
141
+ }
142
+ }
143
+ //# sourceMappingURL=solvapay.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"solvapay.js","sourceRoot":"","sources":["../../src/solvapay.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAWH;;;;;GAKG;AACH,MAAM,OAAO,mBAAmB;IACtB,UAAU,CAAQ;IAE1B,YAAY,MAAiC;QAC3C,IAAI,CAAC,UAAU,GAAG,MAAM,CAAC,UAAU,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CAAA;IACxD,CAAC;IAED,KAAK,CAAC,oBAAoB,CAAC,GAA0B;QACnD,IAAI,CAAC;YACH,MAAM,OAAO,GAAG,SAAS,IAAI,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,GAAG,CAAA;YACpD,MAAM,UAAU,GAAG,OAAO,CAAC,GAAG,CAAC,eAAe,CAAC,CAAA;YAE/C,IAAI,CAAC,UAAU,IAAI,CAAC,UAAU,CAAC,UAAU,CAAC,SAAS,CAAC,EAAE,CAAC;gBACrD,OAAO,IAAI,CAAA;YACb,CAAC;YAED,MAAM,KAAK,GAAG,UAAU,CAAC,KAAK,CAAC,CAAC,CAAC,CAAA;YACjC,IAAI,CAAC,KAAK,EAAE,CAAC;gBACX,OAAO,IAAI,CAAA;YACb,CAAC;YAED,oEAAoE;YACpE,MAAM,QAAQ,GAAG,MAAM,KAAK,CAAC,GAAG,IAAI,CAAC,UAAU,4BAA4B,EAAE;gBAC3E,MAAM,EAAE,KAAK;gBACb,OAAO,EAAE;oBACP,aAAa,EAAE,UAAU,KAAK,EAAE;oBAChC,cAAc,EAAE,kBAAkB;iBACnC;aACF,CAAC,CAAA;YAEF,IAAI,CAAC,QAAQ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ACpD;YACD,IAAI,EAAE,IAAI,CAAC,QAAQ,EAAE;SACtB,CAAC,CAAA;IACJ,CAAC;IAED;;OAEG;IACH,KAAK,CAAC,WAAW,CAAC,WAAmB,EAAE,WAAoB;QACvD,uEAAuE;QACvE,mFAAmF;QACnF,IAAI,CAAC,WAAW,EAAE,CAAC;YACf,MAAM,IAAI,KAAK,CAAC,yBAAyB,CAAC,CAAA;QAC9C,CAAC;QAED,MAAM,QAAQ,GAAG,MAAM,KAAK,CAAC,WAAW,EAAE;YACxC,MAAM,EAAE,KAAK;YACb,OAAO,EAAE;gBACP,aAAa,EAAE,UAAU,WAAW,EAAE;gBACtC,MAAM,EAAE,kBAAkB;aAC3B;SACF,CAAC,CAAA;QAEF,IAAI,CAAC,QAAQ,CAAC,EAAE,EAAE,CAAC;YACjB,MAAM,IAAI,KAAK,CAAC,8BAA8B,QAAQ,CAAC,MAAM,EAAE,CAAC,CAAA;QAClE,CAAC;QAED,OAAO,QAAQ,CAAC,IAAI,EAAsC,CAAA;IAC9D,CAAC;CACF"}
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Supabase Auth Adapter
3
+ *
4
+ * Extracts user ID from Supabase JWT tokens using HS256 verification.
5
+ * Works in both Node.js and Edge runtimes (uses dynamic import for jose).
6
+ */
7
+ import type { AuthAdapter, RequestLike } from './adapter';
8
+ export interface SupabaseAuthAdapterConfig {
9
+ /**
10
+ * Supabase JWT secret (from Supabase dashboard: Settings → API → JWT Secret)
11
+ */
12
+ jwtSecret: string;
13
+ }
14
+ /**
15
+ * Supabase authentication adapter
16
+ *
17
+ * Verifies Supabase JWT tokens and extracts the user ID from the `sub` claim.
18
+ * Uses dynamic import for jose to keep the package lean and Edge-compatible.
19
+ *
20
+ * @example
21
+ * ```ts
22
+ * import { SupabaseAuthAdapter } from '@solvapay/auth/supabase';
23
+ *
24
+ * const auth = new SupabaseAuthAdapter({
25
+ * jwtSecret: process.env.SUPABASE_JWT_SECRET!
26
+ * });
27
+ *
28
+ * const userId = await auth.getUserIdFromRequest(request);
29
+ * if (!userId) {
30
+ * return new Response('Unauthorized', { status: 401 });
31
+ * }
32
+ * ```
33
+ */
34
+ export declare class SupabaseAuthAdapter implements AuthAdapter {
35
+ private jwtSecret;
36
+ constructor(config: SupabaseAuthAdapterConfig);
37
+ getUserIdFromRequest(req: Request | RequestLike): Promise<string | null>;
38
+ }
39
+ //# sourceMappingURL=supabase.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"supabase.d.ts","sourceRoot":"","sources":["../../src/supabase.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,WAAW,CAAA;AAEzD,MAAM,WAAW,yBAAyB;IACxC;;OAEG;IACH,SAAS,EAAE,MAAM,CAAA;CAClB;AAED;;;;;;;;;;;;;;;;;;;GAmBG;AACH,qBAAa,mBAAoB,YAAW,WAAW;IACrD,OAAO,CAAC,SAAS,CAAY;gBAEjB,MAAM,EAAE,yBAAyB;IAOvC,oBAAoB,CAAC,GAAG,EAAE,OAAO,GAAG,WAAW,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC;CA8B/E"}