squarefi-bff-api-module 1.30.9 → 1.31.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.
package/CHANGELOG.md CHANGED
@@ -4,7 +4,302 @@ All notable changes to this project will be documented in this file.
4
4
 
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
- ƒ
7
+
8
+ ## [1.31] - 2025-11-19
9
+
10
+ ### Changed
11
+
12
+ - Updated useFileUpload hook to require bucket and support folder structure for file uploads
13
+ - Removed useUserFiles hook
14
+
15
+ ## [1.30.10] - 2025-11-19
16
+
17
+ ### Added
18
+
19
+ - Added balance and total_balance fields to wallet API response
20
+
21
+ ## [1.30.9] - 2025-11-17
22
+
23
+ ### Changed
24
+
25
+ - Updated wallets API to accept query parameters and renamed type generation script in package.json
26
+
27
+ ## [1.30.8] - 2025-11-14
28
+
29
+ ### Changed
30
+
31
+ - Removed outdated HIFI transaction types and added new L2F transaction types for deposits and withdrawals
32
+ - Updated OrderType enum to include new deposit and withdrawal types for HIFI and L2F
33
+
34
+ ## [1.30.7] - 2025-11-14
35
+
36
+ ### Added
37
+
38
+ - Added HIFI_ACH_WITHDRAWAL and HIFI_ACH_DEPOSIT to OrderType enum
39
+ - Added check-types script to package.json
40
+
41
+ ## [1.30.6] - 2025-11-14
42
+
43
+ ### Changed
44
+
45
+ - Removed DepositInstruction interface and updated deposit_instructions type in VirtualAccountAccountDetails
46
+
47
+ ## [1.30.5] - 2025-11-14
48
+
49
+ ### Added
50
+
51
+ - Added from_crypto_address field to order request parameters in API types
52
+
53
+ ## [1.30.4] - 2025-11-14
54
+
55
+ ### Added
56
+
57
+ - Added OrderTypeKycRail type and updated OrderInfo interface to include order_types_kyc_rails and is_trusted fields
58
+
59
+ ## [1.30.3] - 2025-11-14
60
+
61
+ ### Added
62
+
63
+ - Added OrderPaymentMethod enum and updated OrderInfo interface to use it
64
+
65
+ ## [1.30.2] - 2025-11-12
66
+
67
+ ### Changed
68
+
69
+ - Removed unused OrderMetaExtended type and simplified OrderDetails type definition
70
+
71
+ ## [1.30.1] - 2025-11-12
72
+
73
+ ### Added
74
+
75
+ - Introduced new interfaces for simplified currency and wallet, renamed payment originator types, and extended order meta with additional fields
76
+
77
+ ## [1.30.0] - 2025-11-10
78
+
79
+ ### Added
80
+
81
+ - Added new endpoints for listing orders by wallet and retrieving order details by ID, along with corresponding request/response types
82
+
83
+ ## [1.29.3] - 2025-11-07
84
+
85
+ ### Added
86
+
87
+ - Extended DepositInstruction with CHAPS and FPS instruction types and added sort_code field
88
+
89
+ ## [1.29.2] - 2025-11-07
90
+
91
+ ### Added
92
+
93
+ - Added iban field to ACH interface in API types
94
+
95
+ ## [1.29.1] - 2025-11-07
96
+
97
+ ### Added
98
+
99
+ - Added SEPA_CT instruction type and corresponding SEPA interface to DepositInstruction
100
+
101
+ ## [1.29.0] - 2025-10-29
102
+
103
+ ### Added
104
+
105
+ - Introduced EXCHANGE_OMNI order type and updated related API request/response types
106
+ - Added Supabase Storage integration with user-level security and file management features
107
+
108
+ ## [1.28.0] - 2025-10-27
109
+
110
+ ### Added
111
+
112
+ - Added new order types for card withdrawals and updated API types accordingly
113
+
114
+ ## [1.27.8] - 2025-10-24
115
+
116
+ ### Fixed
117
+
118
+ - Corrected typo in WITHDRAWAL_CRYPTO request type by changing 'is_substract' to 'is_subsctract'
119
+
120
+ ## [1.27.7] - 2025-10-24
121
+
122
+ ### Fixed
123
+
124
+ - Corrected typo in WITHDRAWAL_CRYPTO request type by changing 'is_subtract' to 'is_substract'
125
+
126
+ ## [1.27.6] - 2025-10-24
127
+
128
+ ### Changed
129
+
130
+ - Enhanced tenant config type definition and removed deprecated endpoints for improved clarity and type safety
131
+
132
+ ## [1.27.5] - 2025-10-23
133
+
134
+ ### Fixed
135
+
136
+ - Made virtual_account_id optional in OrderWithVirtualAccountParams for improved flexibility
137
+
138
+ ## [1.27.4] - 2025-10-23
139
+
140
+ ### Changed
141
+
142
+ - Version bump for latest changes
143
+
144
+ ## [1.27.3] - 2025-10-23
145
+
146
+ ### Fixed
147
+
148
+ - Simplified SEGREGATED_CRYPTO_TRANSFER request type by using Omit to exclude to_currency_id for better type safety
149
+
150
+ ## [1.27.2] - 2025-10-23
151
+
152
+ ### Fixed
153
+
154
+ - Updated SEGREGATED_CRYPTO_TRANSFER request type to disallow to_currency_id for improved type safety
155
+
156
+ ## [1.27.1] - 2025-10-23
157
+
158
+ ### Added
159
+
160
+ - Added is_reverse flag to transfer order parameters and refined order type definitions for improved clarity
161
+
162
+ ## [1.27.0] - 2025-10-23
163
+
164
+ ### Changed
165
+
166
+ - Removed HIFI_CRYPTO_TRANSFER order type and consolidated order request/response structures for improved maintainability
167
+
168
+ ### Added
169
+
170
+ - Added new off-ramp order types and corresponding request/response structures for ACH, Wire, SWIFT, and SEPA transactions
171
+ - Added Prettier for code formatting and enhanced OrderType enum with new onramp/offramp types
172
+
173
+ ## [1.26.14] - 2025-10-22
174
+
175
+ ### Fixed
176
+
177
+ - Made deposit_instructions optional in VirtualAccount and VirtualAccountDetailItem interfaces
178
+
179
+ ## [1.26.13] - 2025-10-22
180
+
181
+ ### Changed
182
+
183
+ - Enhanced DepositInstruction types with ACH, FEDWIRE, and SWIFT interfaces and restructured related account information
184
+
185
+ ## [1.26.12] - 2025-10-03
186
+
187
+ ### Changed
188
+
189
+ - Version bump for latest changes
190
+
191
+ ## [1.26.11] - 2025-10-03
192
+
193
+ ### Changed
194
+
195
+ - Version bump for latest changes
196
+
197
+ ## [1.26.10] - 2025-10-03
198
+
199
+ ### Changed
200
+
201
+ - Updated VirtualAccount types to include VirtualAccountDetailItem and renamed VirtualAccountListItem
202
+
203
+ ## [1.26.9] - 2025-10-03
204
+
205
+ ### Added
206
+
207
+ - Added VirtualAccountDetailItem type
208
+
209
+ ### Changed
210
+
211
+ - Formatted type definitions for clarity and added is_enabled field to APIKey interface
212
+
213
+ ## [1.26.8] - 2025-09-19
214
+
215
+ ### Fixed
216
+
217
+ - Corrected type definition for bank data response and updated request field name for consistency
218
+
219
+ ## [1.26.7] - 2025-09-18
220
+
221
+ ### Changed
222
+
223
+ - Version bump for latest changes
224
+
225
+ ## [1.26.6] - 2025-09-18
226
+
227
+ ### Changed
228
+
229
+ - Updated bank data retrieval method to use GET with params for improved clarity and consistency
230
+
231
+ ## [1.26.5] - 2025-09-18
232
+
233
+ ### Fixed
234
+
235
+ - Changed bank data retrieval method from GET to POST for improved data handling
236
+
237
+ ## [1.26.4] - 2025-09-18
238
+
239
+ ### Added
240
+
241
+ - Integrated bank data module and defined TypeScript types for bank data retrieval
242
+
243
+ ## [1.26.3] - 2025-09-16
244
+
245
+ ### Added
246
+
247
+ - Added resume inquiry endpoint and corresponding TypeScript types for enhanced inquiry management
248
+
249
+ ## [1.26.2] - 2025-09-16
250
+
251
+ ### Changed
252
+
253
+ - Deprecated card_limit in favor of max_cards for improved clarity in card management
254
+
255
+ ## [1.26.1] - 2025-09-11
256
+
257
+ ### Fixed
258
+
259
+ - Enhanced unauthorized error handling by adding context check to bypass handler
260
+
261
+ ## [1.26.0] - 2025-09-11
262
+
263
+ ### Fixed
264
+
265
+ - Added context to authentication requests and updated TypeScript configuration to include type definitions
266
+
267
+ ## [1.25.6] - 2025-09-10
268
+
269
+ ### Added
270
+
271
+ - Added new sign-in and sign-up endpoints
272
+
273
+ ## [1.25.5] - 2025-09-05
274
+
275
+ ### Added
276
+
277
+ - Added TOTP status endpoint and response type for improved status tracking
278
+
279
+ ## [1.25.4] - 2025-08-22
280
+
281
+ ### Changed
282
+
283
+ - Updated wallet transaction filter types to use Partial for improved flexibility
284
+
285
+ ## [1.25.3] - 2025-08-22
286
+
287
+ ### Changed
288
+
289
+ - Streamlined wallet transaction filter types by utilizing shared schema for consistency
290
+ - Enhanced ExportCsv request type to include comprehensive filter options for wallet transactions
291
+
292
+ ## [1.25.2] - 2025-08-20
293
+
294
+ ### Fixed
295
+
296
+ - Updated channel initialization to use key prop if provided in subscription hooks
297
+
298
+ ## [1.25.1] - 2025-08-20
299
+
300
+ ### Changed
301
+
302
+ - Simplified useWalletTransactionsSubscription and enhanced useSupabaseSubscription with key prop
8
303
 
9
304
  ## [1.25.0] - 2025-08-19
10
305
 
@@ -0,0 +1,146 @@
1
+ # ✅ Fixed: RLS Policy Error
2
+
3
+ ## ❌ Problem
4
+ ```
5
+ new row violates row-level security policy
6
+ ```
7
+
8
+ ## ✅ Solution
9
+ All functions now accept `authToken` parameter!
10
+
11
+ ## 🚀 Quick Fix
12
+
13
+ ### Before (Error):
14
+ ```typescript
15
+ const result = await uploadFile({
16
+ file: myFile,
17
+ fileName: 'test.pdf',
18
+ userId: 'user-123',
19
+ });
20
+ // ❌ Error: RLS policy violation
21
+ ```
22
+
23
+ ### After (Works):
24
+ ```typescript
25
+ const authToken = 'your-jwt-token'; // From Supabase Auth
26
+
27
+ const result = await uploadFile({
28
+ file: myFile,
29
+ fileName: 'test.pdf',
30
+ userId: 'user-123',
31
+ authToken, // ← Add this!
32
+ });
33
+ // ✅ Success!
34
+ ```
35
+
36
+ ## 📱 React Hook Usage
37
+
38
+ ```typescript
39
+ import { useFileUpload } from 'squarefi-bff-api-module';
40
+
41
+ function MyComponent() {
42
+ const authToken = 'your-jwt-token'; // Get from your auth
43
+
44
+ const { upload } = useFileUpload({
45
+ userId: 'user-123',
46
+ authToken, // ← Add this!
47
+ });
48
+
49
+ return <input type="file" onChange={(e) => upload(e.target.files[0])} />;
50
+ }
51
+ ```
52
+
53
+ ## 🔑 How to Get Auth Token
54
+
55
+ ### Option 1: From Supabase
56
+
57
+ ```typescript
58
+ import { supabaseClient } from 'squarefi-bff-api-module';
59
+
60
+ const { data: { session } } = await supabaseClient.auth.getSession();
61
+ const authToken = session?.access_token;
62
+ ```
63
+
64
+ ### Option 2: From Browser (for testing)
65
+
66
+ 1. Login to your app
67
+ 2. Open Console (F12)
68
+ 3. Run:
69
+ ```javascript
70
+ const session = await supabaseClient.auth.getSession();
71
+ console.log(session.data.session.access_token);
72
+ ```
73
+ 4. Copy the token
74
+
75
+ ### Option 3: From Your Auth System
76
+
77
+ ```typescript
78
+ // From localStorage
79
+ const authToken = localStorage.getItem('access_token');
80
+
81
+ // From auth context
82
+ const { accessToken } = useAuth();
83
+ ```
84
+
85
+ ## 📝 Updated API
86
+
87
+ All these functions now accept `authToken`:
88
+
89
+ | Function | Signature |
90
+ |----------|-----------|
91
+ | `uploadFile` | `uploadFile({..., authToken})` |
92
+ | `getSignedUrl` | `getSignedUrl({..., authToken})` |
93
+ | `deleteFile` | `deleteFile(path, bucket, authToken)` |
94
+ | `deleteFiles` | `deleteFiles(paths, bucket, authToken)` |
95
+ | `listUserFiles` | `listUserFiles(userId, bucket, authToken)` |
96
+ | `downloadFile` | `downloadFile(path, bucket, authToken)` |
97
+
98
+ ## 🧪 Test Example
99
+
100
+ ```typescript
101
+ // 1. Get auth token
102
+ const authToken = 'eyJhbGci...'; // Your JWT token
103
+
104
+ // 2. Upload with token
105
+ const result = await uploadFile({
106
+ file: myFile,
107
+ fileName: 'test.pdf',
108
+ userId: 'user-123',
109
+ authToken,
110
+ });
111
+
112
+ console.log(result.success); // true
113
+ console.log(result.path); // user-123/test.pdf
114
+ ```
115
+
116
+ ## 🔒 Why This Works
117
+
118
+ RLS policies check `auth.uid()` from JWT token:
119
+
120
+ ```sql
121
+ -- Policy requires authenticated user
122
+ WITH CHECK (
123
+ (storage.foldername(name))[1] = auth.uid()::text
124
+ )
125
+ ```
126
+
127
+ - ❌ **Without token**: `auth.uid()` = NULL → Policy fails
128
+ - ✅ **With token**: `auth.uid()` = user ID → Policy passes
129
+
130
+ ## 📚 Full Documentation
131
+
132
+ - **AUTH_TOKEN_USAGE.md** - Complete guide with examples
133
+ - **FRONTEND_STORAGE_GUIDE.md** - React usage
134
+ - **STORAGE_MODULE.md** - Full API reference
135
+
136
+ ## ✅ Changes Summary
137
+
138
+ - ✅ Added `authToken` parameter to all storage functions
139
+ - ✅ Updated hooks (`useFileUpload`, `useUserFiles`)
140
+ - ✅ Backward compatible (token is optional)
141
+ - ✅ Creates authenticated client when token provided
142
+ - ✅ Project builds successfully
143
+
144
+ Now you can upload files from authenticated users! 🎉
145
+
146
+
package/QUICK_TEST.md ADDED
@@ -0,0 +1,127 @@
1
+ # Quick Test Guide ⚡
2
+
3
+ ## ✅ Исправлено!
4
+
5
+ HTML тест был исправлен. Основные проблемы:
6
+ - Неправильная инициализация Supabase клиента
7
+ - Незакрытый тег script
8
+ - Неправильные ссылки на клиент
9
+
10
+ ## 🧪 Как протестировать СЕЙЧАС
11
+
12
+ ### 1. Откройте test-storage.html в браузере
13
+
14
+ Просто двойной клик на файл или:
15
+ ```bash
16
+ open test-storage.html # macOS
17
+ ```
18
+
19
+ ### 2. Что вы должны увидеть
20
+
21
+ ✅ **Зеленый статус** вверху: "✅ Connected to Supabase"
22
+
23
+ ❌ Если видите **красный статус** - проверьте консоль браузера (F12)
24
+
25
+ ### 3. Нажмите "Test Connection"
26
+
27
+ Должно показать:
28
+ ```
29
+ ✅ Connection successful!
30
+
31
+ Available buckets:
32
+ [...список бакетов...]
33
+ ```
34
+
35
+ ### 4. Попробуйте загрузить файл
36
+
37
+ ❌ **Если получите ошибку** типа:
38
+ - "Bucket not found" → Нужно создать бакет (см. ниже)
39
+ - "Permission denied" → Нужно настроить RLS (см. ниже)
40
+
41
+ ## ⚠️ Перед загрузкой файлов
42
+
43
+ Нужно выполнить SQL скрипт в Supabase:
44
+
45
+ 1. Откройте: https://dpwavvgrlklpuoddutdp.supabase.co
46
+ 2. Перейдите в **SQL Editor**
47
+ 3. Скопируйте весь файл `scripts/supabase-storage-setup.sql`
48
+ 4. Вставьте и нажмите **RUN**
49
+
50
+ Это создаст:
51
+ - ✅ Бакеты: user-files, documents, images
52
+ - ✅ RLS политики для безопасности
53
+ - ✅ Функцию is_super_admin()
54
+
55
+ ## 🔍 Ожидаемые результаты
56
+
57
+ ### ✅ Если SQL выполнен:
58
+ - "Test Connection" → Показывает 3 бакета
59
+ - "Upload File" → Файл загружается успешно
60
+ - "List Files" → Показывает загруженные файлы
61
+ - "Get Signed URL" → Генерирует рабочую ссылку
62
+
63
+ ### ❌ Если SQL НЕ выполнен:
64
+ - "Test Connection" → Может показать пустой список бакетов
65
+ - "Upload File" → Ошибка "Bucket not found"
66
+ - "List Files" → Ошибка
67
+
68
+ ## 🚀 Node.js тест (альтернатива)
69
+
70
+ ```bash
71
+ node test-storage.js
72
+ ```
73
+
74
+ Покажет:
75
+ ```
76
+ 🔍 Testing Supabase Storage Module...
77
+
78
+ 1. Testing Supabase client initialization...
79
+ ✅ Supabase client initialized successfully
80
+
81
+ 2. Testing getPublicUrl function...
82
+ ✅ getPublicUrl works
83
+
84
+ ✨ Basic tests completed!
85
+ ```
86
+
87
+ ## 🐛 Troubleshooting
88
+
89
+ ### Консоль показывает "supabase is not defined"
90
+ - Проблема с CDN загрузкой
91
+ - Попробуйте обновить страницу (F5)
92
+ - Проверьте интернет-соединение
93
+
94
+ ### "Failed to fetch"
95
+ - Проверьте URL и ключ в test-storage.html
96
+ - Убедитесь, что Supabase проект активен
97
+
98
+ ### "Bucket not found"
99
+ - Выполните SQL скрипт
100
+ - Проверьте название бакета (должно быть 'user-files')
101
+
102
+ ### Files не загружаются
103
+ - SQL скрипт не выполнен
104
+ - RLS политики не настроены
105
+ - Неправильный формат user ID
106
+
107
+ ## 📊 Что дальше?
108
+
109
+ После успешного теста:
110
+
111
+ 1. ✅ Используйте модуль в React:
112
+ ```tsx
113
+ import { useFileUpload } from 'squarefi-bff-api-module';
114
+ ```
115
+
116
+ 2. ✅ Прочитайте документацию:
117
+ - `docs/FRONTEND_STORAGE_GUIDE.md` - Для React
118
+ - `docs/STORAGE_MODULE.md` - Полное API
119
+ - `docs/STORAGE_QUICK_START.md` - Быстрый старт
120
+
121
+ 3. ✅ Настройте `is_super_admin()` под вашу схему пользователей
122
+
123
+ ## ✨ Готово!
124
+
125
+ Модуль протестирован и готов к использованию!
126
+
127
+
package/README.md CHANGED
@@ -10,6 +10,7 @@ A fully-typed TypeScript / JavaScript SDK for effortless interaction with the Sq
10
10
  • Strict TypeScript types generated from the OpenAPI contract.
11
11
  • Axios-powered HTTP client with automatic tenant & environment headers.
12
12
  • First-class support for **Telegram Mini-Apps** as well as Web.
13
+ • **Supabase Storage integration** with automatic user-level security policies.
13
14
  • Batteries included: constants, helpers & cryptography utilities.
14
15
  • Zero-config – just provide your API URLs and tenant id.
15
16
 
@@ -69,18 +70,22 @@ const { isConnected } = useSupabaseSubscription({
69
70
 
70
71
  The SDK reads connection details from process-level variables. When bundling for the browser, tools like **Vite**, **Webpack DefinePlugin**, or **Next.js** can safely inline those values at build time.
71
72
 
72
- | Name | Description | Required | Example |
73
- | -------------------------- | -------------------------------------------------------------------- | ------------------------------ | ----------------------------- |
74
- | `API_URL` | Base URL of the BFF **v1** service | ✅ | `https://api-v1.squarefi.com` |
75
- | `API_V2_URL` | Base URL of the BFF **v2** service | ✅ | `https://api-v2.squarefi.com` |
76
- | `API_TOTP_URL` | Base URL of the **TOTP / OTP** micro-service | ⚠️ _If you use TOTP features_ | `https://totp.squarefi.com` |
77
- | `TENANT_ID` | Your tenant / organisation identifier | ✅ | `tenant_12345` |
78
- | `LOGOUT_URL` | Frontend route where the user is redirected when refresh token fails | ❌ | `/auth/logout` |
79
- | `SERVER_PUBLIC_KEY_BASE64` | PEM encoded key (base64) used for request signing | ✅ | `MIIBIjANBgkqh…` |
80
- | `SUPABASE_URL` | Supabase project URL for real-time subscriptions | ⚠️ _If you use Supabase hooks_ | `https://xyz.supabase.co` |
81
- | `SUPABASE_PUBLIC_KEY` | Supabase public anon key for client authentication | ⚠️ _If you use Supabase hooks_ | `eyJhbGciOiJIUzI1NiIs…` |
73
+ | Name | Description | Required | Example |
74
+ | -------------------------- | -------------------------------------------------------------------------------------------- | ----------------------------------------- | ----------------------------- |
75
+ | `API_URL` | Base URL of the BFF **v1** service | ✅ | `https://api-v1.squarefi.com` |
76
+ | `API_V2_URL` | Base URL of the BFF **v2** service | ✅ | `https://api-v2.squarefi.com` |
77
+ | `API_TOTP_URL` | Base URL of the **TOTP / OTP** micro-service | ⚠️ _If you use TOTP features_ | `https://totp.squarefi.com` |
78
+ | `TENANT_ID` | Your tenant / organisation identifier | ✅ | `tenant_12345` |
79
+ | `LOGOUT_URL` | Frontend route where the user is redirected when refresh token fails | ❌ | `/auth/logout` |
80
+ | `SERVER_PUBLIC_KEY_BASE64` | PEM encoded key (base64) used for encrypted sensitive data requests (e.g., card secret keys) | ✅ | `MIIBIjANBgkqh…` |
81
+ | `SUPABASE_URL` | Supabase project URL for real-time subscriptions and file storage | ⚠️ _If you use Supabase hooks or Storage_ | `https://xyz.supabase.co` |
82
+ | `SUPABASE_PUBLIC_KEY` | Supabase public anon key for client authentication | ⚠️ _If you use Supabase hooks or Storage_ | `eyJhbGciOiJIUzI1NiIs…` |
83
+
84
+ > ⚠️ **Backend Only**: `SUPABASE_SERVICE_ROLE_KEY` is used for backend file access (see [Backend Service URL Guide](./docs/BACKEND_SERVICE_URL.md)). **Never expose this key on frontend/client-side code.**
82
85
 
83
86
  > ℹ️ When running in Node.js you can place these variables in a `.env` file and load them with [dotenv](https://npmjs.com/package/dotenv).
87
+ >
88
+ > 📝 See `env.example` file in the repository root for a complete template with all available environment variables.
84
89
 
85
90
  ---
86
91
 
@@ -122,6 +127,78 @@ function MyComponent() {
122
127
 
123
128
  ---
124
129
 
130
+ ## 📦 Supabase Storage Module
131
+
132
+ The SDK includes a complete file storage solution powered by Supabase Storage with automatic user-level security policies. Files are automatically organized by user ID and protected with Row Level Security (RLS).
133
+
134
+ ### Quick Start
135
+
136
+ ```ts
137
+ import { uploadFile, getSignedUrl, DEFAULT_BUCKET } from 'squarefi-bff-api-module';
138
+
139
+ // Upload a file
140
+ const result = await uploadFile({
141
+ file: myFile, // File or Blob
142
+ fileName: 'document.pdf',
143
+ userId: 'user-uuid',
144
+ bucket: DEFAULT_BUCKET,
145
+ });
146
+
147
+ if (result.success) {
148
+ console.log('File uploaded:', result.path);
149
+ console.log('Signed URL:', result.signedUrl); // Use this for secure access
150
+ }
151
+
152
+ // Get a signed URL for accessing the file
153
+ const signedUrl = await getSignedUrl({
154
+ path: result.path,
155
+ expiresIn: 3600, // 1 hour
156
+ });
157
+ ```
158
+
159
+ ### Features
160
+
161
+ - ✅ Automatic file organization by user ID (`{userId}/{fileName}`)
162
+ - ✅ Row Level Security (RLS) - users can only access their own files
163
+ - ✅ Superadmin access to all files (configurable)
164
+ - ✅ Multiple storage buckets: `user-files`, `documents`, `images`
165
+ - ✅ Signed URLs for temporary secure access
166
+ - ✅ Service URLs for permanent backend access (with service role key)
167
+ - ✅ File listing, deletion, and download support
168
+
169
+ ### URL Types
170
+
171
+ | Type | Expires | Use Case | Authentication |
172
+ | -------------- | ----------------------- | --------------------------- | ------------------------------ |
173
+ | **Signed URL** | ✅ Yes (1 hour default) | End users, temporary access | ❌ Not required |
174
+ | **Public URL** | ❌ Never | Backend/Superadmin access | ✅ Required (service role key) |
175
+
176
+ ```typescript
177
+ // For end users (temporary, no auth needed)
178
+ const signedUrl = await getSignedUrl({ path, expiresIn: 3600 });
179
+
180
+ // For superadmin backend (permanent, requires service key)
181
+ const publicUrl = getPublicUrl(path);
182
+ // On backend: fetch(publicUrl, { headers: { 'Authorization': 'Bearer SERVICE_KEY' } })
183
+ ```
184
+
185
+ ### Setup
186
+
187
+ 1. Set required environment variables (see table above)
188
+ 2. Run the SQL setup script in your Supabase project:
189
+ ```bash
190
+ # Execute scripts/supabase-storage-setup.sql in Supabase SQL Editor
191
+ ```
192
+ 3. Customize the `is_super_admin()` function according to your user schema
193
+
194
+ 📖 **Documentation**:
195
+
196
+ - **Frontend Guide** (React): [docs/FRONTEND_STORAGE_GUIDE.md](./docs/FRONTEND_STORAGE_GUIDE.md) - Quick start with ready-to-use components
197
+ - **Full Documentation**: [docs/STORAGE_MODULE.md](./docs/STORAGE_MODULE.md) - Detailed API description
198
+ - **Quick Start**: [docs/STORAGE_QUICK_START.md](./docs/STORAGE_QUICK_START.md) - Get started in 5 minutes
199
+
200
+ ---
201
+
125
202
  ## 🗺️ API surface
126
203
 
127
204
  `squarefi_bff_api_client` is a plain object where every property is a namespaced group of operations. The list below reflects the current SDK version (v1.18.13).