naystack 1.1.13-beta.3 → 1.1.13

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,157 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/file/put.ts
21
+ var put_exports = {};
22
+ __export(put_exports, {
23
+ getFileUploadPutRoute: () => getFileUploadPutRoute
24
+ });
25
+ module.exports = __toCommonJS(put_exports);
26
+ var import_functions2 = require("@vercel/functions");
27
+ var import_server3 = require("next/server");
28
+ var import_uuid = require("uuid");
29
+
30
+ // src/auth/email/utils.ts
31
+ var import_jsonwebtoken2 = require("jsonwebtoken");
32
+
33
+ // src/auth/email/token.ts
34
+ var import_bcryptjs = require("bcryptjs");
35
+ var import_jsonwebtoken = require("jsonwebtoken");
36
+ var import_server = require("next/server");
37
+ function getUserIdFromRefreshToken(refreshKey, refreshToken) {
38
+ if (refreshToken)
39
+ try {
40
+ const decoded = (0, import_jsonwebtoken.verify)(refreshToken, refreshKey);
41
+ if (typeof decoded !== "string" && typeof decoded.id === "number")
42
+ return decoded.id;
43
+ } catch (e) {
44
+ if (!(e instanceof import_jsonwebtoken.JsonWebTokenError)) console.error(e, "errors");
45
+ return null;
46
+ }
47
+ return null;
48
+ }
49
+
50
+ // src/auth/utils/errors.ts
51
+ var import_server2 = require("next/server");
52
+
53
+ // src/auth/email/utils.ts
54
+ var getUserContext = (refreshKey, signingKey, req) => {
55
+ const bearer = req.headers.get("authorization");
56
+ if (!bearer) {
57
+ const refresh = req.cookies.get("refresh")?.value;
58
+ const userId = getUserIdFromRefreshToken(refreshKey, refresh);
59
+ if (userId) return { refreshUserID: userId };
60
+ return null;
61
+ }
62
+ const token = bearer.slice(7);
63
+ try {
64
+ const res = (0, import_jsonwebtoken2.verify)(token, signingKey);
65
+ if (typeof res === "string") {
66
+ return null;
67
+ }
68
+ return {
69
+ accessUserId: res.id
70
+ };
71
+ } catch {
72
+ }
73
+ return null;
74
+ };
75
+
76
+ // src/file/utils.ts
77
+ var import_node_crypto = require("crypto");
78
+ var import_client_s3 = require("@aws-sdk/client-s3");
79
+ var import_s3_request_presigner = require("@aws-sdk/s3-request-presigner");
80
+ var import_functions = require("@vercel/functions");
81
+ var getURLPrefix = (options) => `https://${options.bucket}.s3.${options.region}.amazonaws.com/`;
82
+ function getHash(keys) {
83
+ return (0, import_node_crypto.createHash)("sha256").update(keys.join("/")).digest("hex");
84
+ }
85
+ var getFileURL = (options) => (keys) => {
86
+ if (typeof keys === "string") return `${getURLPrefix(options)}${keys}`;
87
+ return `${getURLPrefix(options)}${getHash(keys)}`;
88
+ };
89
+ var deleteImage = (client, options) => async (url) => {
90
+ const key = url.split(getURLPrefix(options))[1];
91
+ if (key) {
92
+ try {
93
+ await client.send(
94
+ new import_client_s3.DeleteObjectCommand({
95
+ Bucket: options.bucket,
96
+ Key: key
97
+ })
98
+ );
99
+ return true;
100
+ } catch (e) {
101
+ console.error("ERROR", url, e);
102
+ }
103
+ }
104
+ return false;
105
+ };
106
+ var uploadFile = (client, Bucket) => async (file, key) => {
107
+ const fileBuffer = await file.arrayBuffer();
108
+ return client.send(
109
+ new import_client_s3.PutObjectCommand({
110
+ Bucket,
111
+ Key: key,
112
+ ACL: "public-read",
113
+ Body: Buffer.from(fileBuffer),
114
+ ContentType: file.type,
115
+ ContentLength: file.size
116
+ })
117
+ );
118
+ };
119
+
120
+ // src/file/put.ts
121
+ var getFileUploadPutRoute = (options, client) => async (req) => {
122
+ const ctx = getUserContext(options.refreshKey, options.signingKey, req);
123
+ if (!ctx?.accessUserId)
124
+ return import_server3.NextResponse.json({ error: "unauthorized" }, { status: 401 });
125
+ const formData = await req.formData();
126
+ const type = formData.get("type");
127
+ const sync = Boolean(formData.get("sync"));
128
+ const file = formData.get("file");
129
+ const data = formData.get("data");
130
+ const imageKey = (0, import_uuid.v4)();
131
+ const url = file ? getFileURL(options)(imageKey) : null;
132
+ const handleKeyProcessing = async () => {
133
+ if (file) await uploadFile(client, options.bucket)(file, imageKey);
134
+ if (!type || !ctx.accessUserId) return;
135
+ const { deleteURL, response } = await options.processFile({
136
+ url,
137
+ type,
138
+ userId: ctx.accessUserId,
139
+ data: typeof data === "string" ? JSON.parse(data) : void 0
140
+ });
141
+ if (deleteURL) await deleteImage(client, options)(deleteURL);
142
+ return response;
143
+ };
144
+ if (!sync) {
145
+ (0, import_functions2.waitUntil)(handleKeyProcessing());
146
+ return import_server3.NextResponse.json({ url });
147
+ } else {
148
+ return import_server3.NextResponse.json({
149
+ url,
150
+ response: await handleKeyProcessing()
151
+ });
152
+ }
153
+ };
154
+ // Annotate the CommonJS export names for ESM import in node:
155
+ 0 && (module.exports = {
156
+ getFileUploadPutRoute
157
+ });
@@ -0,0 +1,11 @@
1
+ import { S3Client } from '@aws-sdk/client-s3';
2
+ import { NextRequest, NextResponse } from 'next/server';
3
+ import { SetupFileUploadOptions } from './setup.mjs';
4
+
5
+ declare const getFileUploadPutRoute: (options: SetupFileUploadOptions, client: S3Client) => (req: NextRequest) => Promise<NextResponse<{
6
+ error: string;
7
+ }> | NextResponse<{
8
+ url: string | null;
9
+ }>>;
10
+
11
+ export { getFileUploadPutRoute };
@@ -0,0 +1,11 @@
1
+ import { S3Client } from '@aws-sdk/client-s3';
2
+ import { NextRequest, NextResponse } from 'next/server';
3
+ import { SetupFileUploadOptions } from './setup.js';
4
+
5
+ declare const getFileUploadPutRoute: (options: SetupFileUploadOptions, client: S3Client) => (req: NextRequest) => Promise<NextResponse<{
6
+ error: string;
7
+ }> | NextResponse<{
8
+ url: string | null;
9
+ }>>;
10
+
11
+ export { getFileUploadPutRoute };
@@ -0,0 +1,136 @@
1
+ // src/file/put.ts
2
+ import { waitUntil as waitUntil2 } from "@vercel/functions";
3
+ import { NextResponse as NextResponse3 } from "next/server";
4
+ import { v4 } from "uuid";
5
+
6
+ // src/auth/email/utils.ts
7
+ import { verify as verify2 } from "jsonwebtoken";
8
+
9
+ // src/auth/email/token.ts
10
+ import { compare } from "bcryptjs";
11
+ import { JsonWebTokenError, sign, verify } from "jsonwebtoken";
12
+ import { NextResponse } from "next/server";
13
+ function getUserIdFromRefreshToken(refreshKey, refreshToken) {
14
+ if (refreshToken)
15
+ try {
16
+ const decoded = verify(refreshToken, refreshKey);
17
+ if (typeof decoded !== "string" && typeof decoded.id === "number")
18
+ return decoded.id;
19
+ } catch (e) {
20
+ if (!(e instanceof JsonWebTokenError)) console.error(e, "errors");
21
+ return null;
22
+ }
23
+ return null;
24
+ }
25
+
26
+ // src/auth/utils/errors.ts
27
+ import { NextResponse as NextResponse2 } from "next/server";
28
+
29
+ // src/auth/email/utils.ts
30
+ var getUserContext = (refreshKey, signingKey, req) => {
31
+ const bearer = req.headers.get("authorization");
32
+ if (!bearer) {
33
+ const refresh = req.cookies.get("refresh")?.value;
34
+ const userId = getUserIdFromRefreshToken(refreshKey, refresh);
35
+ if (userId) return { refreshUserID: userId };
36
+ return null;
37
+ }
38
+ const token = bearer.slice(7);
39
+ try {
40
+ const res = verify2(token, signingKey);
41
+ if (typeof res === "string") {
42
+ return null;
43
+ }
44
+ return {
45
+ accessUserId: res.id
46
+ };
47
+ } catch {
48
+ }
49
+ return null;
50
+ };
51
+
52
+ // src/file/utils.ts
53
+ import { createHash } from "crypto";
54
+ import {
55
+ DeleteObjectCommand,
56
+ PutObjectCommand,
57
+ S3Client
58
+ } from "@aws-sdk/client-s3";
59
+ import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
60
+ import { waitUntil } from "@vercel/functions";
61
+ var getURLPrefix = (options) => `https://${options.bucket}.s3.${options.region}.amazonaws.com/`;
62
+ function getHash(keys) {
63
+ return createHash("sha256").update(keys.join("/")).digest("hex");
64
+ }
65
+ var getFileURL = (options) => (keys) => {
66
+ if (typeof keys === "string") return `${getURLPrefix(options)}${keys}`;
67
+ return `${getURLPrefix(options)}${getHash(keys)}`;
68
+ };
69
+ var deleteImage = (client, options) => async (url) => {
70
+ const key = url.split(getURLPrefix(options))[1];
71
+ if (key) {
72
+ try {
73
+ await client.send(
74
+ new DeleteObjectCommand({
75
+ Bucket: options.bucket,
76
+ Key: key
77
+ })
78
+ );
79
+ return true;
80
+ } catch (e) {
81
+ console.error("ERROR", url, e);
82
+ }
83
+ }
84
+ return false;
85
+ };
86
+ var uploadFile = (client, Bucket) => async (file, key) => {
87
+ const fileBuffer = await file.arrayBuffer();
88
+ return client.send(
89
+ new PutObjectCommand({
90
+ Bucket,
91
+ Key: key,
92
+ ACL: "public-read",
93
+ Body: Buffer.from(fileBuffer),
94
+ ContentType: file.type,
95
+ ContentLength: file.size
96
+ })
97
+ );
98
+ };
99
+
100
+ // src/file/put.ts
101
+ var getFileUploadPutRoute = (options, client) => async (req) => {
102
+ const ctx = getUserContext(options.refreshKey, options.signingKey, req);
103
+ if (!ctx?.accessUserId)
104
+ return NextResponse3.json({ error: "unauthorized" }, { status: 401 });
105
+ const formData = await req.formData();
106
+ const type = formData.get("type");
107
+ const sync = Boolean(formData.get("sync"));
108
+ const file = formData.get("file");
109
+ const data = formData.get("data");
110
+ const imageKey = v4();
111
+ const url = file ? getFileURL(options)(imageKey) : null;
112
+ const handleKeyProcessing = async () => {
113
+ if (file) await uploadFile(client, options.bucket)(file, imageKey);
114
+ if (!type || !ctx.accessUserId) return;
115
+ const { deleteURL, response } = await options.processFile({
116
+ url,
117
+ type,
118
+ userId: ctx.accessUserId,
119
+ data: typeof data === "string" ? JSON.parse(data) : void 0
120
+ });
121
+ if (deleteURL) await deleteImage(client, options)(deleteURL);
122
+ return response;
123
+ };
124
+ if (!sync) {
125
+ waitUntil2(handleKeyProcessing());
126
+ return NextResponse3.json({ url });
127
+ } else {
128
+ return NextResponse3.json({
129
+ url,
130
+ response: await handleKeyProcessing()
131
+ });
132
+ }
133
+ };
134
+ export {
135
+ getFileUploadPutRoute
136
+ };
@@ -0,0 +1,195 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/file/setup.ts
21
+ var setup_exports = {};
22
+ __export(setup_exports, {
23
+ setupFileUpload: () => setupFileUpload
24
+ });
25
+ module.exports = __toCommonJS(setup_exports);
26
+
27
+ // src/file/put.ts
28
+ var import_functions2 = require("@vercel/functions");
29
+ var import_server3 = require("next/server");
30
+ var import_uuid = require("uuid");
31
+
32
+ // src/auth/email/utils.ts
33
+ var import_jsonwebtoken2 = require("jsonwebtoken");
34
+
35
+ // src/auth/email/token.ts
36
+ var import_bcryptjs = require("bcryptjs");
37
+ var import_jsonwebtoken = require("jsonwebtoken");
38
+ var import_server = require("next/server");
39
+ function getUserIdFromRefreshToken(refreshKey, refreshToken) {
40
+ if (refreshToken)
41
+ try {
42
+ const decoded = (0, import_jsonwebtoken.verify)(refreshToken, refreshKey);
43
+ if (typeof decoded !== "string" && typeof decoded.id === "number")
44
+ return decoded.id;
45
+ } catch (e) {
46
+ if (!(e instanceof import_jsonwebtoken.JsonWebTokenError)) console.error(e, "errors");
47
+ return null;
48
+ }
49
+ return null;
50
+ }
51
+
52
+ // src/auth/utils/errors.ts
53
+ var import_server2 = require("next/server");
54
+
55
+ // src/auth/email/utils.ts
56
+ var getUserContext = (refreshKey, signingKey, req) => {
57
+ const bearer = req.headers.get("authorization");
58
+ if (!bearer) {
59
+ const refresh = req.cookies.get("refresh")?.value;
60
+ const userId = getUserIdFromRefreshToken(refreshKey, refresh);
61
+ if (userId) return { refreshUserID: userId };
62
+ return null;
63
+ }
64
+ const token = bearer.slice(7);
65
+ try {
66
+ const res = (0, import_jsonwebtoken2.verify)(token, signingKey);
67
+ if (typeof res === "string") {
68
+ return null;
69
+ }
70
+ return {
71
+ accessUserId: res.id
72
+ };
73
+ } catch {
74
+ }
75
+ return null;
76
+ };
77
+
78
+ // src/file/utils.ts
79
+ var import_node_crypto = require("crypto");
80
+ var import_client_s3 = require("@aws-sdk/client-s3");
81
+ var import_s3_request_presigner = require("@aws-sdk/s3-request-presigner");
82
+ var import_functions = require("@vercel/functions");
83
+ var getS3Client = (options) => new import_client_s3.S3Client({
84
+ region: options.region,
85
+ credentials: {
86
+ accessKeyId: options.awsKey,
87
+ secretAccessKey: options.awsSecret
88
+ }
89
+ });
90
+ var getURLPrefix = (options) => `https://${options.bucket}.s3.${options.region}.amazonaws.com/`;
91
+ function getHash(keys) {
92
+ return (0, import_node_crypto.createHash)("sha256").update(keys.join("/")).digest("hex");
93
+ }
94
+ var getUploadFileURL = (client, Bucket) => (keys, isPublic) => {
95
+ const command = new import_client_s3.PutObjectCommand({
96
+ Bucket,
97
+ Key: getHash(keys),
98
+ ACL: isPublic ? "public-read" : void 0
99
+ });
100
+ return (0, import_s3_request_presigner.getSignedUrl)(client, command, { expiresIn: 300 });
101
+ };
102
+ var getFileURL = (options) => (keys) => {
103
+ if (typeof keys === "string") return `${getURLPrefix(options)}${keys}`;
104
+ return `${getURLPrefix(options)}${getHash(keys)}`;
105
+ };
106
+ var uploadImage = (client, options) => async (url, key, blob) => {
107
+ const photoBlob = blob || await fetch(url).then((file) => file.blob());
108
+ if (photoBlob) {
109
+ (0, import_functions.waitUntil)(uploadFile(client, options.bucket)(photoBlob, getHash(key)));
110
+ return getFileURL(options)(key);
111
+ }
112
+ return null;
113
+ };
114
+ var deleteImage = (client, options) => async (url) => {
115
+ const key = url.split(getURLPrefix(options))[1];
116
+ if (key) {
117
+ try {
118
+ await client.send(
119
+ new import_client_s3.DeleteObjectCommand({
120
+ Bucket: options.bucket,
121
+ Key: key
122
+ })
123
+ );
124
+ return true;
125
+ } catch (e) {
126
+ console.error("ERROR", url, e);
127
+ }
128
+ }
129
+ return false;
130
+ };
131
+ var uploadFile = (client, Bucket) => async (file, key) => {
132
+ const fileBuffer = await file.arrayBuffer();
133
+ return client.send(
134
+ new import_client_s3.PutObjectCommand({
135
+ Bucket,
136
+ Key: key,
137
+ ACL: "public-read",
138
+ Body: Buffer.from(fileBuffer),
139
+ ContentType: file.type,
140
+ ContentLength: file.size
141
+ })
142
+ );
143
+ };
144
+
145
+ // src/file/put.ts
146
+ var getFileUploadPutRoute = (options, client) => async (req) => {
147
+ const ctx = getUserContext(options.refreshKey, options.signingKey, req);
148
+ if (!ctx?.accessUserId)
149
+ return import_server3.NextResponse.json({ error: "unauthorized" }, { status: 401 });
150
+ const formData = await req.formData();
151
+ const type = formData.get("type");
152
+ const sync = Boolean(formData.get("sync"));
153
+ const file = formData.get("file");
154
+ const data = formData.get("data");
155
+ const imageKey = (0, import_uuid.v4)();
156
+ const url = file ? getFileURL(options)(imageKey) : null;
157
+ const handleKeyProcessing = async () => {
158
+ if (file) await uploadFile(client, options.bucket)(file, imageKey);
159
+ if (!type || !ctx.accessUserId) return;
160
+ const { deleteURL, response } = await options.processFile({
161
+ url,
162
+ type,
163
+ userId: ctx.accessUserId,
164
+ data: typeof data === "string" ? JSON.parse(data) : void 0
165
+ });
166
+ if (deleteURL) await deleteImage(client, options)(deleteURL);
167
+ return response;
168
+ };
169
+ if (!sync) {
170
+ (0, import_functions2.waitUntil)(handleKeyProcessing());
171
+ return import_server3.NextResponse.json({ url });
172
+ } else {
173
+ return import_server3.NextResponse.json({
174
+ url,
175
+ response: await handleKeyProcessing()
176
+ });
177
+ }
178
+ };
179
+
180
+ // src/file/setup.ts
181
+ function setupFileUpload(options) {
182
+ const client = getS3Client(options);
183
+ return {
184
+ PUT: getFileUploadPutRoute(options, client),
185
+ getUploadFileURL: getUploadFileURL(client, options.bucket),
186
+ uploadImage: uploadImage(client, options),
187
+ deleteImage: deleteImage(client, options),
188
+ getFileURL: getFileURL(options),
189
+ uploadFile: uploadFile(client, options.bucket)
190
+ };
191
+ }
192
+ // Annotate the CommonJS export names for ESM import in node:
193
+ 0 && (module.exports = {
194
+ setupFileUpload
195
+ });
@@ -0,0 +1,34 @@
1
+ import * as _aws_sdk_client_s3 from '@aws-sdk/client-s3';
2
+ import * as next_server from 'next/server';
3
+
4
+ interface SetupFileUploadOptions {
5
+ refreshKey: string;
6
+ signingKey: string;
7
+ region: string;
8
+ bucket: string;
9
+ awsSecret: string;
10
+ awsKey: string;
11
+ processFile: (data: {
12
+ url: string | null;
13
+ type: string;
14
+ userId: number;
15
+ data: object;
16
+ }) => Promise<{
17
+ deleteURL?: string;
18
+ response?: object;
19
+ }>;
20
+ }
21
+ declare function setupFileUpload(options: SetupFileUploadOptions): {
22
+ PUT: (req: next_server.NextRequest) => Promise<next_server.NextResponse<{
23
+ error: string;
24
+ }> | next_server.NextResponse<{
25
+ url: string | null;
26
+ }>>;
27
+ getUploadFileURL: (keys: string[], isPublic?: boolean) => Promise<string>;
28
+ uploadImage: (url: string, key: string[], blob?: Blob) => Promise<string | null>;
29
+ deleteImage: (url: string) => Promise<boolean>;
30
+ getFileURL: (keys: string | string[]) => string;
31
+ uploadFile: (file: File | Blob, key: string) => Promise<_aws_sdk_client_s3.PutObjectCommandOutput>;
32
+ };
33
+
34
+ export { type SetupFileUploadOptions, setupFileUpload };
@@ -0,0 +1,34 @@
1
+ import * as _aws_sdk_client_s3 from '@aws-sdk/client-s3';
2
+ import * as next_server from 'next/server';
3
+
4
+ interface SetupFileUploadOptions {
5
+ refreshKey: string;
6
+ signingKey: string;
7
+ region: string;
8
+ bucket: string;
9
+ awsSecret: string;
10
+ awsKey: string;
11
+ processFile: (data: {
12
+ url: string | null;
13
+ type: string;
14
+ userId: number;
15
+ data: object;
16
+ }) => Promise<{
17
+ deleteURL?: string;
18
+ response?: object;
19
+ }>;
20
+ }
21
+ declare function setupFileUpload(options: SetupFileUploadOptions): {
22
+ PUT: (req: next_server.NextRequest) => Promise<next_server.NextResponse<{
23
+ error: string;
24
+ }> | next_server.NextResponse<{
25
+ url: string | null;
26
+ }>>;
27
+ getUploadFileURL: (keys: string[], isPublic?: boolean) => Promise<string>;
28
+ uploadImage: (url: string, key: string[], blob?: Blob) => Promise<string | null>;
29
+ deleteImage: (url: string) => Promise<boolean>;
30
+ getFileURL: (keys: string | string[]) => string;
31
+ uploadFile: (file: File | Blob, key: string) => Promise<_aws_sdk_client_s3.PutObjectCommandOutput>;
32
+ };
33
+
34
+ export { type SetupFileUploadOptions, setupFileUpload };