@zuiio/supabase 0.1.0 → 0.2.1
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 +21 -0
- package/dist/api-response.d.ts +25 -0
- package/dist/api-response.d.ts.map +1 -0
- package/{src/api-response.ts → dist/api-response.js} +8 -16
- package/dist/api-response.js.map +1 -0
- package/dist/auth.d.ts +27 -0
- package/dist/auth.d.ts.map +1 -0
- package/dist/auth.js +55 -0
- package/dist/auth.js.map +1 -0
- package/dist/errors.d.ts +7 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +36 -0
- package/dist/errors.js.map +1 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +7 -0
- package/dist/index.js.map +1 -0
- package/dist/query.d.ts +30 -0
- package/dist/query.d.ts.map +1 -0
- package/dist/query.js +74 -0
- package/dist/query.js.map +1 -0
- package/dist/r2-storage.d.ts +24 -0
- package/dist/r2-storage.d.ts.map +1 -0
- package/dist/r2-storage.js +78 -0
- package/dist/r2-storage.js.map +1 -0
- package/dist/storage.d.ts +20 -0
- package/dist/storage.d.ts.map +1 -0
- package/dist/storage.js +38 -0
- package/dist/storage.js.map +1 -0
- package/dist/turnstile.d.ts +13 -0
- package/dist/turnstile.d.ts.map +1 -0
- package/dist/turnstile.js +45 -0
- package/dist/turnstile.js.map +1 -0
- package/dist/with-batch.d.ts +69 -0
- package/dist/with-batch.d.ts.map +1 -0
- package/dist/with-batch.js +130 -0
- package/dist/with-batch.js.map +1 -0
- package/{src/with-org-branch-filter.ts → dist/with-org-branch-filter.d.ts} +2 -4
- package/dist/with-org-branch-filter.d.ts.map +1 -0
- package/dist/with-org-branch-filter.js +22 -0
- package/dist/with-org-branch-filter.js.map +1 -0
- package/{src/with-org-scope.ts → dist/with-org-scope.d.ts} +2 -4
- package/dist/with-org-scope.d.ts.map +1 -0
- package/dist/with-org-scope.js +26 -0
- package/dist/with-org-scope.js.map +1 -0
- package/dist/with-pagination.d.ts +17 -0
- package/dist/with-pagination.d.ts.map +1 -0
- package/{src/with-pagination.ts → dist/with-pagination.js} +7 -10
- package/dist/with-pagination.js.map +1 -0
- package/dist/workers-ai.d.ts +33 -0
- package/dist/workers-ai.d.ts.map +1 -0
- package/dist/workers-ai.js +114 -0
- package/dist/workers-ai.js.map +1 -0
- package/package.json +54 -18
- package/AGENTS.md +0 -84
- package/src/auth.ts +0 -86
- package/src/errors.ts +0 -42
- package/src/index.ts +0 -7
- package/src/query.ts +0 -108
- package/src/r2-storage.ts +0 -98
- package/src/storage.ts +0 -68
- package/src/turnstile.ts +0 -61
- package/src/with-batch.ts +0 -172
- package/src/workers-ai.ts +0 -172
- package/tsconfig.json +0 -7
package/package.json
CHANGED
|
@@ -1,27 +1,63 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@zuiio/supabase",
|
|
3
|
-
"version": "0.1
|
|
3
|
+
"version": "0.2.1",
|
|
4
|
+
"description": "Supabase server utilities — auth, query, storage, R2, Turnstile, Workers AI",
|
|
5
|
+
"license": "MIT",
|
|
4
6
|
"type": "module",
|
|
5
|
-
"
|
|
6
|
-
"
|
|
7
|
-
"
|
|
8
|
-
"./errors": "./src/errors.ts",
|
|
9
|
-
"./query": "./src/query.ts",
|
|
10
|
-
"./storage": "./src/storage.ts",
|
|
11
|
-
"./turnstile": "./src/turnstile.ts",
|
|
12
|
-
"./r2-storage": "./src/r2-storage.ts",
|
|
13
|
-
"./workers-ai": "./src/workers-ai.ts"
|
|
7
|
+
"dependencies": {
|
|
8
|
+
"@aws-sdk/client-s3": "^3.1081.0",
|
|
9
|
+
"@aws-sdk/s3-request-presigner": "^3.1081.0"
|
|
14
10
|
},
|
|
15
11
|
"peerDependencies": {
|
|
16
12
|
"@supabase/supabase-js": "^2"
|
|
17
13
|
},
|
|
18
|
-
"
|
|
19
|
-
"
|
|
20
|
-
"
|
|
21
|
-
"
|
|
14
|
+
"repository": {
|
|
15
|
+
"type": "git",
|
|
16
|
+
"url": "git+https://github.com/themuuln/zuiio.git",
|
|
17
|
+
"directory": "packages/supabase"
|
|
22
18
|
},
|
|
23
|
-
"
|
|
24
|
-
"
|
|
25
|
-
|
|
19
|
+
"files": [
|
|
20
|
+
"dist"
|
|
21
|
+
],
|
|
22
|
+
"exports": {
|
|
23
|
+
".": {
|
|
24
|
+
"types": "./dist/index.d.ts",
|
|
25
|
+
"default": "./dist/index.js"
|
|
26
|
+
},
|
|
27
|
+
"./auth": {
|
|
28
|
+
"types": "./dist/auth.d.ts",
|
|
29
|
+
"default": "./dist/auth.js"
|
|
30
|
+
},
|
|
31
|
+
"./errors": {
|
|
32
|
+
"types": "./dist/errors.d.ts",
|
|
33
|
+
"default": "./dist/errors.js"
|
|
34
|
+
},
|
|
35
|
+
"./query": {
|
|
36
|
+
"types": "./dist/query.d.ts",
|
|
37
|
+
"default": "./dist/query.js"
|
|
38
|
+
},
|
|
39
|
+
"./storage": {
|
|
40
|
+
"types": "./dist/storage.d.ts",
|
|
41
|
+
"default": "./dist/storage.js"
|
|
42
|
+
},
|
|
43
|
+
"./turnstile": {
|
|
44
|
+
"types": "./dist/turnstile.d.ts",
|
|
45
|
+
"default": "./dist/turnstile.js"
|
|
46
|
+
},
|
|
47
|
+
"./r2-storage": {
|
|
48
|
+
"types": "./dist/r2-storage.d.ts",
|
|
49
|
+
"default": "./dist/r2-storage.js"
|
|
50
|
+
},
|
|
51
|
+
"./workers-ai": {
|
|
52
|
+
"types": "./dist/workers-ai.d.ts",
|
|
53
|
+
"default": "./dist/workers-ai.js"
|
|
54
|
+
}
|
|
55
|
+
},
|
|
56
|
+
"types": "./dist/index.d.ts",
|
|
57
|
+
"main": "./dist/index.js",
|
|
58
|
+
"module": "./dist/index.js",
|
|
59
|
+
"publishConfig": {
|
|
60
|
+
"registry": "https://registry.npmjs.org",
|
|
61
|
+
"access": "public"
|
|
26
62
|
}
|
|
27
|
-
}
|
|
63
|
+
}
|
package/AGENTS.md
DELETED
|
@@ -1,84 +0,0 @@
|
|
|
1
|
-
# @zuiio/supabase
|
|
2
|
-
|
|
3
|
-
Supabase utilities for server-side operations. Provides auth helpers, query wrappers, storage utilities, and error handling.
|
|
4
|
-
|
|
5
|
-
## Exports
|
|
6
|
-
|
|
7
|
-
| Module | Description |
|
|
8
|
-
|--------|-------------|
|
|
9
|
-
| `auth` | Server-side auth helpers (getSession, getUser, etc.) |
|
|
10
|
-
| `errors` | Supabase error handling and sanitization |
|
|
11
|
-
| `query` | Query helpers (withDbCapture, paginate, etc.) |
|
|
12
|
-
| `storage` | Storage upload/download helpers |
|
|
13
|
-
|
|
14
|
-
## Usage
|
|
15
|
-
|
|
16
|
-
### Server auth
|
|
17
|
-
|
|
18
|
-
```ts
|
|
19
|
-
import { getSession, getUser } from "@zuiio/supabase/auth";
|
|
20
|
-
|
|
21
|
-
// Get current session (server-side)
|
|
22
|
-
const session = await getSession(supabase);
|
|
23
|
-
|
|
24
|
-
// Get current user (throws if not authenticated)
|
|
25
|
-
const user = await getUser(supabase);
|
|
26
|
-
```
|
|
27
|
-
|
|
28
|
-
### Error handling
|
|
29
|
-
|
|
30
|
-
```ts
|
|
31
|
-
import { sanitizeDbError, isRLSError } from "@zuiio/supabase/errors";
|
|
32
|
-
|
|
33
|
-
const { data, error } = await supabase.from("table").select("*");
|
|
34
|
-
|
|
35
|
-
if (error) {
|
|
36
|
-
// Sanitize for user-facing messages
|
|
37
|
-
const message = sanitizeDbError(error);
|
|
38
|
-
// "Датаны алдаа" (not raw PostgREST error)
|
|
39
|
-
|
|
40
|
-
// Check if it's an RLS error
|
|
41
|
-
if (isRLSError(error)) {
|
|
42
|
-
// Handle permission denied
|
|
43
|
-
}
|
|
44
|
-
}
|
|
45
|
-
```
|
|
46
|
-
|
|
47
|
-
### Query helpers
|
|
48
|
-
|
|
49
|
-
```ts
|
|
50
|
-
import { withDbCapture } from "@zuiio/supabase/query";
|
|
51
|
-
|
|
52
|
-
// Auto-capture Supabase errors (best practice)
|
|
53
|
-
const { data, error } = await withDbCapture("getProfile",
|
|
54
|
-
supabase.from("profiles").select("*").single()
|
|
55
|
-
);
|
|
56
|
-
|
|
57
|
-
// Error is logged to Sentry automatically
|
|
58
|
-
// No need for manual capture() calls
|
|
59
|
-
```
|
|
60
|
-
|
|
61
|
-
### Storage
|
|
62
|
-
|
|
63
|
-
```ts
|
|
64
|
-
import { uploadImage, downloadFile } from "@zuiio/supabase/storage";
|
|
65
|
-
|
|
66
|
-
// Upload with automatic optimization
|
|
67
|
-
const url = await uploadImage(supabase, "avatars", file, {
|
|
68
|
-
maxWidth: 800,
|
|
69
|
-
quality: 0.8,
|
|
70
|
-
});
|
|
71
|
-
|
|
72
|
-
// Download file
|
|
73
|
-
const blob = await downloadFile(supabase, "documents", "file.pdf");
|
|
74
|
-
```
|
|
75
|
-
|
|
76
|
-
## Dependencies
|
|
77
|
-
|
|
78
|
-
- `@supabase/supabase-js` — Supabase client
|
|
79
|
-
|
|
80
|
-
## Notes
|
|
81
|
-
|
|
82
|
-
- Server-side only — use `@zuiio/auth` for client-side auth
|
|
83
|
-
- Always use `withDbCapture()` for queries — catches silent RLS errors
|
|
84
|
-
- `sanitizeDbError()` returns Mongolian error messages
|
package/src/auth.ts
DELETED
|
@@ -1,86 +0,0 @@
|
|
|
1
|
-
import type { SupabaseClient, User } from "@supabase/supabase-js";
|
|
2
|
-
|
|
3
|
-
export class AuthRequiredError extends Error {
|
|
4
|
-
constructor() {
|
|
5
|
-
super("Нэвтрэх шаардлагатай");
|
|
6
|
-
this.name = "AuthRequiredError";
|
|
7
|
-
}
|
|
8
|
-
}
|
|
9
|
-
|
|
10
|
-
export class ForbiddenError extends Error {
|
|
11
|
-
constructor(message = "Хандах эрх байхгүй") {
|
|
12
|
-
super(message);
|
|
13
|
-
this.name = "ForbiddenError";
|
|
14
|
-
}
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
/** Get the current user or throw AuthRequiredError. */
|
|
18
|
-
export async function withAuth(supabase: SupabaseClient): Promise<User> {
|
|
19
|
-
const {
|
|
20
|
-
data: { user },
|
|
21
|
-
error,
|
|
22
|
-
} = await supabase.auth.getUser();
|
|
23
|
-
if (error || !user) throw new AuthRequiredError();
|
|
24
|
-
return user;
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
/** Get current session or null — non-throwing. */
|
|
28
|
-
export async function getSession(supabase: SupabaseClient) {
|
|
29
|
-
const {
|
|
30
|
-
data: { session },
|
|
31
|
-
} = await supabase.auth.getSession();
|
|
32
|
-
return session;
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
/** Get user ID or null without throwing. */
|
|
36
|
-
export async function getUserId(
|
|
37
|
-
supabase: SupabaseClient,
|
|
38
|
-
): Promise<string | null> {
|
|
39
|
-
const {
|
|
40
|
-
data: { user },
|
|
41
|
-
} = await supabase.auth.getUser();
|
|
42
|
-
return user?.id ?? null;
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
/**
|
|
46
|
-
* Check if the current user belongs to an org.
|
|
47
|
-
* Assumes a table named `org_members` with columns `org_id`, `user_id`, `role`.
|
|
48
|
-
* Pass your own table/column names via options if your schema differs.
|
|
49
|
-
*/
|
|
50
|
-
export async function getOrgRole(
|
|
51
|
-
supabase: SupabaseClient,
|
|
52
|
-
orgId: string,
|
|
53
|
-
userId: string,
|
|
54
|
-
opts?: {
|
|
55
|
-
table?: string;
|
|
56
|
-
orgCol?: string;
|
|
57
|
-
userCol?: string;
|
|
58
|
-
roleCol?: string;
|
|
59
|
-
},
|
|
60
|
-
): Promise<string | null> {
|
|
61
|
-
const table = opts?.table ?? "org_members";
|
|
62
|
-
const orgCol = opts?.orgCol ?? "org_id";
|
|
63
|
-
const userCol = opts?.userCol ?? "user_id";
|
|
64
|
-
const roleCol = opts?.roleCol ?? "role";
|
|
65
|
-
|
|
66
|
-
const { data } = await supabase
|
|
67
|
-
.from(table)
|
|
68
|
-
.select(roleCol)
|
|
69
|
-
.eq(orgCol, orgId)
|
|
70
|
-
.eq(userCol, userId)
|
|
71
|
-
.single();
|
|
72
|
-
|
|
73
|
-
return (data as Record<string, string> | null)?.[roleCol] ?? null;
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
/** Require org membership — throws ForbiddenError if not a member. */
|
|
77
|
-
export async function requireOrgMember(
|
|
78
|
-
supabase: SupabaseClient,
|
|
79
|
-
orgId: string,
|
|
80
|
-
userId: string,
|
|
81
|
-
opts?: Parameters<typeof getOrgRole>[3],
|
|
82
|
-
): Promise<string> {
|
|
83
|
-
const role = await getOrgRole(supabase, orgId, userId, opts);
|
|
84
|
-
if (!role) throw new ForbiddenError();
|
|
85
|
-
return role;
|
|
86
|
-
}
|
package/src/errors.ts
DELETED
|
@@ -1,42 +0,0 @@
|
|
|
1
|
-
import type { AuthError, PostgrestError } from "@supabase/supabase-js";
|
|
2
|
-
|
|
3
|
-
const POSTGREST_MESSAGES: Record<string, string> = {
|
|
4
|
-
"42501": "Хандах эрх байхгүй",
|
|
5
|
-
"23503": "Холбоотой өгөгдөл байна — устгах боломжгүй",
|
|
6
|
-
"23505": "Энэ утга аль хэдийн бүртгэлтэй байна",
|
|
7
|
-
PGRST116: "Өгөгдөл олдсонгүй",
|
|
8
|
-
PGRST204: "Хүсэлтийн баганын нэр буруу байна",
|
|
9
|
-
};
|
|
10
|
-
|
|
11
|
-
export function parseRLSError(error: PostgrestError): string {
|
|
12
|
-
return POSTGREST_MESSAGES[error.code] ?? error.message;
|
|
13
|
-
}
|
|
14
|
-
|
|
15
|
-
export function parseAuthError(error: AuthError): string {
|
|
16
|
-
const msg = error.message.toLowerCase();
|
|
17
|
-
if (msg.includes("invalid login credentials"))
|
|
18
|
-
return "Нэвтрэх нэр эсвэл нууц үг буруу байна";
|
|
19
|
-
if (msg.includes("email not confirmed"))
|
|
20
|
-
return "И-мэйл хаягаа баталгаажуулна уу";
|
|
21
|
-
if (msg.includes("user already registered"))
|
|
22
|
-
return "Энэ и-мэйл хаяг аль хэдийн бүртгэлтэй байна";
|
|
23
|
-
if (msg.includes("password should be at least"))
|
|
24
|
-
return "Нууц үг хамгийн багадаа 6 тэмдэгт байх ёстой";
|
|
25
|
-
if (msg.includes("email rate limit exceeded"))
|
|
26
|
-
return "Хэт олон оролдлого хийгдлээ. Түр хүлээнэ үү";
|
|
27
|
-
if (msg.includes("token has expired"))
|
|
28
|
-
return "Холбоос хугацаа дууссан байна. Дахин оролдоно уу";
|
|
29
|
-
return error.message;
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
export function isRLSError(error: PostgrestError): boolean {
|
|
33
|
-
return error.code === "42501";
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
export function isUniqueViolation(error: PostgrestError): boolean {
|
|
37
|
-
return error.code === "23505";
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
export function isForeignKeyViolation(error: PostgrestError): boolean {
|
|
41
|
-
return error.code === "23503";
|
|
42
|
-
}
|
package/src/index.ts
DELETED
package/src/query.ts
DELETED
|
@@ -1,108 +0,0 @@
|
|
|
1
|
-
import type { SupabaseClient } from "@supabase/supabase-js";
|
|
2
|
-
|
|
3
|
-
export interface ListOptions {
|
|
4
|
-
/** Column to order by (default: "created_at") */
|
|
5
|
-
orderBy?: string;
|
|
6
|
-
ascending?: boolean;
|
|
7
|
-
/** Supabase .range() args — use paginate() from @zer/core */
|
|
8
|
-
from?: number;
|
|
9
|
-
to?: number;
|
|
10
|
-
/** Column equality filters, e.g. { org_id: "abc", status: "active" } */
|
|
11
|
-
filters?: Record<string, unknown>;
|
|
12
|
-
}
|
|
13
|
-
|
|
14
|
-
export interface QueryResult<T> {
|
|
15
|
-
data: T[];
|
|
16
|
-
count: number | null;
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
/**
|
|
20
|
-
* Generic CRUD factory — pass your Supabase client + table name, get typed list/get/create/update/remove.
|
|
21
|
-
*
|
|
22
|
-
* @example
|
|
23
|
-
* const products = createSimpleQuery<Product>(supabase, "products");
|
|
24
|
-
* const { data } = await products.list({ filters: { org_id: orgId } });
|
|
25
|
-
*/
|
|
26
|
-
export function createSimpleQuery<T extends Record<string, unknown>>(
|
|
27
|
-
supabase: SupabaseClient,
|
|
28
|
-
table: string,
|
|
29
|
-
) {
|
|
30
|
-
return {
|
|
31
|
-
async list(opts: ListOptions = {}): Promise<QueryResult<T>> {
|
|
32
|
-
const {
|
|
33
|
-
orderBy = "created_at",
|
|
34
|
-
ascending = false,
|
|
35
|
-
from,
|
|
36
|
-
to,
|
|
37
|
-
filters,
|
|
38
|
-
} = opts;
|
|
39
|
-
|
|
40
|
-
let q = supabase
|
|
41
|
-
.from(table)
|
|
42
|
-
.select("*", { count: "exact" })
|
|
43
|
-
.order(orderBy, { ascending });
|
|
44
|
-
|
|
45
|
-
if (filters) {
|
|
46
|
-
for (const [col, val] of Object.entries(filters)) {
|
|
47
|
-
if (val !== undefined && val !== null) {
|
|
48
|
-
q = q.eq(col, val);
|
|
49
|
-
}
|
|
50
|
-
}
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
if (from !== undefined && to !== undefined) {
|
|
54
|
-
q = q.range(from, to);
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
const { data, error, count } = await q;
|
|
58
|
-
if (error) throw error;
|
|
59
|
-
return { data: (data ?? []) as T[], count };
|
|
60
|
-
},
|
|
61
|
-
|
|
62
|
-
async getById(id: string): Promise<T | null> {
|
|
63
|
-
const { data, error } = await supabase
|
|
64
|
-
.from(table)
|
|
65
|
-
.select("*")
|
|
66
|
-
.eq("id", id)
|
|
67
|
-
.single();
|
|
68
|
-
if (error) {
|
|
69
|
-
if (error.code === "PGRST116") return null;
|
|
70
|
-
throw error;
|
|
71
|
-
}
|
|
72
|
-
return data as T;
|
|
73
|
-
},
|
|
74
|
-
|
|
75
|
-
async create(
|
|
76
|
-
record: Omit<T, "id" | "created_at" | "updated_at">,
|
|
77
|
-
): Promise<T> {
|
|
78
|
-
const { data, error } = await supabase
|
|
79
|
-
.from(table)
|
|
80
|
-
// biome-ignore lint/suspicious/noExplicitAny: Supabase generic mismatch with Omit<T,...>
|
|
81
|
-
.insert(record as any)
|
|
82
|
-
.select()
|
|
83
|
-
.single();
|
|
84
|
-
if (error) throw error;
|
|
85
|
-
return data as T;
|
|
86
|
-
},
|
|
87
|
-
|
|
88
|
-
async update(
|
|
89
|
-
id: string,
|
|
90
|
-
record: Partial<Omit<T, "id" | "created_at">>,
|
|
91
|
-
): Promise<T> {
|
|
92
|
-
const { data, error } = await supabase
|
|
93
|
-
.from(table)
|
|
94
|
-
// biome-ignore lint/suspicious/noExplicitAny: Supabase generic mismatch with Partial<Omit<T,...>>
|
|
95
|
-
.update(record as any)
|
|
96
|
-
.eq("id", id)
|
|
97
|
-
.select()
|
|
98
|
-
.single();
|
|
99
|
-
if (error) throw error;
|
|
100
|
-
return data as T;
|
|
101
|
-
},
|
|
102
|
-
|
|
103
|
-
async remove(id: string): Promise<void> {
|
|
104
|
-
const { error } = await supabase.from(table).delete().eq("id", id);
|
|
105
|
-
if (error) throw error;
|
|
106
|
-
},
|
|
107
|
-
};
|
|
108
|
-
}
|
package/src/r2-storage.ts
DELETED
|
@@ -1,98 +0,0 @@
|
|
|
1
|
-
import { GetObjectCommand, PutObjectCommand, S3Client } from "@aws-sdk/client-s3";
|
|
2
|
-
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
|
|
3
|
-
|
|
4
|
-
/**
|
|
5
|
-
* Cloudflare R2 client — S3-compatible object storage with zero egress fees.
|
|
6
|
-
*
|
|
7
|
-
* Env vars required:
|
|
8
|
-
* R2_ACCOUNT_ID — Cloudflare account ID
|
|
9
|
-
* R2_ACCESS_KEY_ID — R2 API token access key ID
|
|
10
|
-
* R2_SECRET_ACCESS_KEY — R2 API token secret
|
|
11
|
-
* R2_BUCKET — Default bucket name (optional, can override per call)
|
|
12
|
-
* R2_PUBLIC_DOMAIN — Custom domain or r2.dev pub token (optional)
|
|
13
|
-
*/
|
|
14
|
-
function getR2Client(): S3Client {
|
|
15
|
-
const accountId = process.env.R2_ACCOUNT_ID;
|
|
16
|
-
const accessKeyId = process.env.R2_ACCESS_KEY_ID;
|
|
17
|
-
const secretAccessKey = process.env.R2_SECRET_ACCESS_KEY;
|
|
18
|
-
|
|
19
|
-
if (!accountId || !accessKeyId || !secretAccessKey) {
|
|
20
|
-
throw new Error(
|
|
21
|
-
"R2 not configured. Set R2_ACCOUNT_ID, R2_ACCESS_KEY_ID, and R2_SECRET_ACCESS_KEY.",
|
|
22
|
-
);
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
return new S3Client({
|
|
26
|
-
region: "auto",
|
|
27
|
-
endpoint: `https://${accountId}.r2.cloudflarestorage.com`,
|
|
28
|
-
credentials: { accessKeyId, secretAccessKey },
|
|
29
|
-
});
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
function getDefaultBucket(): string {
|
|
33
|
-
const bucket = process.env.R2_BUCKET;
|
|
34
|
-
if (!bucket) throw new Error("R2_BUCKET not configured.");
|
|
35
|
-
return bucket;
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
/**
|
|
39
|
-
* Upload a file to R2 and return its public URL.
|
|
40
|
-
*/
|
|
41
|
-
export async function uploadToR2(
|
|
42
|
-
key: string,
|
|
43
|
-
body: Buffer | Uint8Array | ReadableStream,
|
|
44
|
-
opts: { bucket?: string; contentType?: string } = {},
|
|
45
|
-
): Promise<string> {
|
|
46
|
-
const client = getR2Client();
|
|
47
|
-
const bucket = opts.bucket ?? getDefaultBucket();
|
|
48
|
-
|
|
49
|
-
await client.send(
|
|
50
|
-
new PutObjectCommand({
|
|
51
|
-
Bucket: bucket,
|
|
52
|
-
Key: key,
|
|
53
|
-
Body: body,
|
|
54
|
-
ContentType: opts.contentType,
|
|
55
|
-
}),
|
|
56
|
-
);
|
|
57
|
-
|
|
58
|
-
return getR2PublicUrl(key, bucket);
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
/**
|
|
62
|
-
* Generate a presigned URL for reading a private file (expires in seconds).
|
|
63
|
-
*/
|
|
64
|
-
export async function getR2SignedUrl(
|
|
65
|
-
key: string,
|
|
66
|
-
opts: { bucket?: string; expiresIn?: number } = {},
|
|
67
|
-
): Promise<string> {
|
|
68
|
-
const client = getR2Client();
|
|
69
|
-
const bucket = opts.bucket ?? getDefaultBucket();
|
|
70
|
-
const expiresIn = opts.expiresIn ?? 3600;
|
|
71
|
-
|
|
72
|
-
const command = new GetObjectCommand({ Bucket: bucket, Key: key });
|
|
73
|
-
return getSignedUrl(client, command, { expiresIn });
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
/**
|
|
77
|
-
* Build a public URL for an R2 object.
|
|
78
|
-
* Uses R2_PUBLIC_DOMAIN env var if set, otherwise falls back to r2.dev.
|
|
79
|
-
*/
|
|
80
|
-
export function getR2PublicUrl(key: string, bucket?: string): string {
|
|
81
|
-
const publicDomain = process.env.R2_PUBLIC_DOMAIN;
|
|
82
|
-
if (publicDomain) {
|
|
83
|
-
return `https://${publicDomain}/${key}`;
|
|
84
|
-
}
|
|
85
|
-
const b = bucket ?? getDefaultBucket();
|
|
86
|
-
// R2 dev subdomain pattern: pub-<token>.r2.dev/<key>
|
|
87
|
-
// User should set R2_PUBLIC_DOMAIN for production
|
|
88
|
-
return `https://${b}.r2.dev/${key}`;
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
/**
|
|
92
|
-
* Build a deterministic storage path: `{prefix}/{uuid}.{ext}`
|
|
93
|
-
*/
|
|
94
|
-
export function buildR2Path(prefix: string, filename: string): string {
|
|
95
|
-
const ext = filename.split(".").pop() ?? "bin";
|
|
96
|
-
const uuid = crypto.randomUUID();
|
|
97
|
-
return `${prefix}/${uuid}.${ext}`;
|
|
98
|
-
}
|
package/src/storage.ts
DELETED
|
@@ -1,68 +0,0 @@
|
|
|
1
|
-
import type { SupabaseClient } from "@supabase/supabase-js";
|
|
2
|
-
|
|
3
|
-
export interface UploadOptions {
|
|
4
|
-
/** Replace existing file at path (default: true) */
|
|
5
|
-
upsert?: boolean;
|
|
6
|
-
contentType?: string;
|
|
7
|
-
/** Cache-Control header (default: "3600") */
|
|
8
|
-
cacheControl?: string;
|
|
9
|
-
}
|
|
10
|
-
|
|
11
|
-
/**
|
|
12
|
-
* Upload a file and return its public URL.
|
|
13
|
-
* Works in browser, React Native (use FormData/Blob), and Node (use Buffer/ArrayBuffer).
|
|
14
|
-
*/
|
|
15
|
-
export async function uploadFile(
|
|
16
|
-
supabase: SupabaseClient,
|
|
17
|
-
bucket: string,
|
|
18
|
-
path: string,
|
|
19
|
-
file: File | Blob | ArrayBuffer | FormData,
|
|
20
|
-
opts: UploadOptions = {},
|
|
21
|
-
): Promise<string> {
|
|
22
|
-
const { upsert = true, contentType, cacheControl = "3600" } = opts;
|
|
23
|
-
|
|
24
|
-
const { error } = await supabase.storage.from(bucket).upload(path, file, {
|
|
25
|
-
upsert,
|
|
26
|
-
contentType,
|
|
27
|
-
cacheControl,
|
|
28
|
-
});
|
|
29
|
-
|
|
30
|
-
if (error) throw error;
|
|
31
|
-
|
|
32
|
-
const {
|
|
33
|
-
data: { publicUrl },
|
|
34
|
-
} = supabase.storage.from(bucket).getPublicUrl(path);
|
|
35
|
-
|
|
36
|
-
return publicUrl;
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
/** Remove one or more files from a bucket. */
|
|
40
|
-
export async function removeFiles(
|
|
41
|
-
supabase: SupabaseClient,
|
|
42
|
-
bucket: string,
|
|
43
|
-
paths: string[],
|
|
44
|
-
): Promise<void> {
|
|
45
|
-
const { error } = await supabase.storage.from(bucket).remove(paths);
|
|
46
|
-
if (error) throw error;
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
/** Get a signed (temporary) URL for a private file. */
|
|
50
|
-
export async function getSignedUrl(
|
|
51
|
-
supabase: SupabaseClient,
|
|
52
|
-
bucket: string,
|
|
53
|
-
path: string,
|
|
54
|
-
expiresInSeconds = 3600,
|
|
55
|
-
): Promise<string> {
|
|
56
|
-
const { data, error } = await supabase.storage
|
|
57
|
-
.from(bucket)
|
|
58
|
-
.createSignedUrl(path, expiresInSeconds);
|
|
59
|
-
if (error) throw error;
|
|
60
|
-
return data.signedUrl;
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
/** Build a deterministic storage path: `{prefix}/{uuid}.{ext}` */
|
|
64
|
-
export function buildStoragePath(prefix: string, filename: string): string {
|
|
65
|
-
const ext = filename.split(".").pop() ?? "bin";
|
|
66
|
-
const uuid = crypto.randomUUID();
|
|
67
|
-
return `${prefix}/${uuid}.${ext}`;
|
|
68
|
-
}
|
package/src/turnstile.ts
DELETED
|
@@ -1,61 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Validate a Cloudflare Turnstile token server-side.
|
|
3
|
-
* Call this in server actions / API routes after the client submits the form.
|
|
4
|
-
*
|
|
5
|
-
* @param token - The `cf-turnstile-response` value from the hidden form field
|
|
6
|
-
* @param remoteIp - Optional: the user's IP for extra validation
|
|
7
|
-
* @returns `{ success: true }` or `{ success: false, error: string }`
|
|
8
|
-
*/
|
|
9
|
-
export async function validateTurnstile(
|
|
10
|
-
token: string | null | undefined,
|
|
11
|
-
remoteIp?: string,
|
|
12
|
-
): Promise<{ success: boolean; error?: string }> {
|
|
13
|
-
// Always skip in development — the widget isn't rendered there
|
|
14
|
-
if (process.env.NODE_ENV === "development") {
|
|
15
|
-
return { success: true };
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
const secretKey = process.env.CLOUDFLARE_TURNSTILE_SECRET_KEY;
|
|
19
|
-
if (!secretKey) {
|
|
20
|
-
if (!token) {
|
|
21
|
-
return { success: false, error: "Missing Turnstile token" };
|
|
22
|
-
}
|
|
23
|
-
return { success: false, error: "Bot protection not configured" };
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
if (!token) {
|
|
27
|
-
return { success: false, error: "Missing Turnstile token" };
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
const formData = new URLSearchParams();
|
|
31
|
-
formData.append("secret", secretKey);
|
|
32
|
-
formData.append("response", token);
|
|
33
|
-
if (remoteIp) {
|
|
34
|
-
formData.append("remoteip", remoteIp);
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
try {
|
|
38
|
-
const res = await fetch(
|
|
39
|
-
"https://challenges.cloudflare.com/turnstile/v0/siteverify",
|
|
40
|
-
{
|
|
41
|
-
method: "POST",
|
|
42
|
-
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
43
|
-
body: formData.toString(),
|
|
44
|
-
},
|
|
45
|
-
);
|
|
46
|
-
|
|
47
|
-
const result = (await res.json()) as {
|
|
48
|
-
success: boolean;
|
|
49
|
-
"error-codes"?: string[];
|
|
50
|
-
};
|
|
51
|
-
|
|
52
|
-
if (!result.success) {
|
|
53
|
-
return { success: false, error: "Bot verification failed" };
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
return { success: true };
|
|
57
|
-
} catch {
|
|
58
|
-
// Fail open on network errors to avoid locking out users
|
|
59
|
-
return { success: true };
|
|
60
|
-
}
|
|
61
|
-
}
|