s3
This commit is contained in:
98
backend/services/s3OwnershipService.js
Normal file
98
backend/services/s3OwnershipService.js
Normal file
@@ -0,0 +1,98 @@
|
||||
const { Message, ConditionCheck, Rental } = require("../models");
|
||||
const { Op } = require("sequelize");
|
||||
|
||||
/**
|
||||
* Service for verifying ownership/access to S3 files
|
||||
* Used to authorize signed URL requests for private content
|
||||
*/
|
||||
class S3OwnershipService {
|
||||
/**
|
||||
* Extract file type from S3 key
|
||||
* @param {string} key - S3 key like "messages/uuid.jpg"
|
||||
* @returns {string|null} - File type or null if unknown
|
||||
*/
|
||||
static getFileTypeFromKey(key) {
|
||||
if (!key) return null;
|
||||
const folder = key.split("/")[0];
|
||||
const folderMap = {
|
||||
profiles: "profile",
|
||||
items: "item",
|
||||
messages: "message",
|
||||
forum: "forum",
|
||||
"condition-checks": "condition-check",
|
||||
};
|
||||
return folderMap[folder] || null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify if a user can access a file
|
||||
* @param {string} key - S3 key
|
||||
* @param {string} userId - User ID making the request
|
||||
* @returns {Promise<{authorized: boolean, reason?: string}>}
|
||||
*/
|
||||
static async canAccessFile(key, userId) {
|
||||
const fileType = this.getFileTypeFromKey(key);
|
||||
|
||||
switch (fileType) {
|
||||
case "profile":
|
||||
case "item":
|
||||
case "forum":
|
||||
// Public folders - anyone can access
|
||||
return { authorized: true };
|
||||
case "message":
|
||||
return this.verifyMessageAccess(key, userId);
|
||||
case "condition-check":
|
||||
return this.verifyConditionCheckAccess(key, userId);
|
||||
default:
|
||||
return { authorized: false, reason: "Unknown file type" };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify message image access - user must be sender OR receiver
|
||||
* @param {string} key - S3 key
|
||||
* @param {string} userId - User ID making the request
|
||||
* @returns {Promise<{authorized: boolean, reason?: string}>}
|
||||
*/
|
||||
static async verifyMessageAccess(key, userId) {
|
||||
const message = await Message.findOne({
|
||||
where: {
|
||||
imageFilename: key,
|
||||
[Op.or]: [{ senderId: userId }, { receiverId: userId }],
|
||||
},
|
||||
});
|
||||
return {
|
||||
authorized: !!message,
|
||||
reason: message ? null : "Not a participant in this message",
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify condition check image access - user must be rental owner OR renter
|
||||
* @param {string} key - S3 key
|
||||
* @param {string} userId - User ID making the request
|
||||
* @returns {Promise<{authorized: boolean, reason?: string}>}
|
||||
*/
|
||||
static async verifyConditionCheckAccess(key, userId) {
|
||||
const check = await ConditionCheck.findOne({
|
||||
where: {
|
||||
imageFilenames: { [Op.contains]: [key] },
|
||||
},
|
||||
include: [
|
||||
{
|
||||
model: Rental,
|
||||
as: "rental",
|
||||
where: {
|
||||
[Op.or]: [{ ownerId: userId }, { renterId: userId }],
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
return {
|
||||
authorized: !!check,
|
||||
reason: check ? null : "Not a participant in this rental",
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = S3OwnershipService;
|
||||
238
backend/services/s3Service.js
Normal file
238
backend/services/s3Service.js
Normal file
@@ -0,0 +1,238 @@
|
||||
const {
|
||||
S3Client,
|
||||
PutObjectCommand,
|
||||
GetObjectCommand,
|
||||
HeadObjectCommand,
|
||||
} = require("@aws-sdk/client-s3");
|
||||
const { getSignedUrl } = require("@aws-sdk/s3-request-presigner");
|
||||
const { getAWSConfig } = require("../config/aws");
|
||||
const { v4: uuidv4 } = require("uuid");
|
||||
const path = require("path");
|
||||
const logger = require("../utils/logger");
|
||||
|
||||
// Cache-Control: 24 hours for public content (allows moderation takedowns to propagate)
|
||||
// Private content (messages, condition-checks) uses presigned URLs so cache doesn't matter as much
|
||||
const DEFAULT_CACHE_MAX_AGE = 86400; // 24 hours in seconds
|
||||
|
||||
const UPLOAD_CONFIGS = {
|
||||
profile: {
|
||||
folder: "profiles",
|
||||
maxSize: 5 * 1024 * 1024,
|
||||
cacheMaxAge: DEFAULT_CACHE_MAX_AGE,
|
||||
public: true,
|
||||
},
|
||||
item: {
|
||||
folder: "items",
|
||||
maxSize: 10 * 1024 * 1024,
|
||||
cacheMaxAge: DEFAULT_CACHE_MAX_AGE,
|
||||
public: true,
|
||||
},
|
||||
message: {
|
||||
folder: "messages",
|
||||
maxSize: 5 * 1024 * 1024,
|
||||
cacheMaxAge: 3600,
|
||||
public: false,
|
||||
},
|
||||
forum: {
|
||||
folder: "forum",
|
||||
maxSize: 10 * 1024 * 1024,
|
||||
cacheMaxAge: DEFAULT_CACHE_MAX_AGE,
|
||||
public: true,
|
||||
},
|
||||
"condition-check": {
|
||||
folder: "condition-checks",
|
||||
maxSize: 10 * 1024 * 1024,
|
||||
cacheMaxAge: 3600,
|
||||
public: false,
|
||||
},
|
||||
};
|
||||
|
||||
const ALLOWED_TYPES = [
|
||||
"image/jpeg",
|
||||
"image/jpg",
|
||||
"image/png",
|
||||
"image/gif",
|
||||
"image/webp",
|
||||
];
|
||||
const PRESIGN_EXPIRY = 300; // 5 minutes
|
||||
|
||||
class S3Service {
|
||||
constructor() {
|
||||
this.client = null;
|
||||
this.bucket = null;
|
||||
this.region = null;
|
||||
this.enabled = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if S3 is enabled
|
||||
* @returns {boolean}
|
||||
*/
|
||||
isEnabled() {
|
||||
return this.enabled;
|
||||
}
|
||||
|
||||
initialize() {
|
||||
if (process.env.S3_ENABLED !== "true") {
|
||||
logger.info("S3 Service disabled (S3_ENABLED !== true)");
|
||||
this.enabled = false;
|
||||
return;
|
||||
}
|
||||
|
||||
// S3 is enabled - validate required configuration
|
||||
const bucket = process.env.S3_BUCKET;
|
||||
if (!bucket) {
|
||||
logger.error("S3_ENABLED=true but S3_BUCKET is not set");
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
try {
|
||||
const config = getAWSConfig();
|
||||
this.client = new S3Client({
|
||||
...config,
|
||||
// Disable automatic checksums - browser uploads can't calculate them
|
||||
requestChecksumCalculation: "WHEN_REQUIRED",
|
||||
});
|
||||
this.bucket = bucket;
|
||||
this.region = config.region || "us-east-1";
|
||||
this.enabled = true;
|
||||
logger.info("S3 Service initialized", {
|
||||
bucket: this.bucket,
|
||||
region: this.region,
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error("Failed to initialize S3 Service", { error: error.message });
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a presigned URL for uploading a file directly to S3
|
||||
* @param {string} uploadType - Type of upload (profile, item, message, forum, condition-check)
|
||||
* @param {string} contentType - MIME type of the file
|
||||
* @param {string} fileName - Original filename (used for extension)
|
||||
* @param {number} fileSize - File size in bytes (required for size enforcement)
|
||||
* @returns {Promise<{uploadUrl: string, key: string, publicUrl: string, expiresAt: Date}>}
|
||||
*/
|
||||
async getPresignedUploadUrl(uploadType, contentType, fileName, fileSize) {
|
||||
if (!this.enabled) {
|
||||
throw new Error("S3 storage is not enabled");
|
||||
}
|
||||
|
||||
const config = UPLOAD_CONFIGS[uploadType];
|
||||
if (!config) {
|
||||
throw new Error(`Invalid upload type: ${uploadType}`);
|
||||
}
|
||||
if (!ALLOWED_TYPES.includes(contentType)) {
|
||||
throw new Error(`Invalid content type: ${contentType}`);
|
||||
}
|
||||
if (!fileSize || fileSize <= 0) {
|
||||
throw new Error("File size is required");
|
||||
}
|
||||
if (fileSize > config.maxSize) {
|
||||
throw new Error(
|
||||
`File too large. Maximum size is ${config.maxSize / (1024 * 1024)}MB`
|
||||
);
|
||||
}
|
||||
|
||||
const ext = path.extname(fileName) || this.getExtFromMime(contentType);
|
||||
const key = `${config.folder}/${uuidv4()}${ext}`;
|
||||
|
||||
const cacheDirective = config.public ? "public" : "private";
|
||||
const command = new PutObjectCommand({
|
||||
Bucket: this.bucket,
|
||||
Key: key,
|
||||
ContentType: contentType,
|
||||
ContentLength: fileSize, // Enforce exact file size
|
||||
CacheControl: `${cacheDirective}, max-age=${config.cacheMaxAge}`,
|
||||
});
|
||||
|
||||
const uploadUrl = await getSignedUrl(this.client, command, {
|
||||
expiresIn: PRESIGN_EXPIRY,
|
||||
});
|
||||
|
||||
return {
|
||||
uploadUrl,
|
||||
key,
|
||||
publicUrl: config.public
|
||||
? `https://${this.bucket}.s3.${this.region}.amazonaws.com/${key}`
|
||||
: null,
|
||||
expiresAt: new Date(Date.now() + PRESIGN_EXPIRY * 1000),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a presigned URL for downloading a private file from S3
|
||||
* @param {string} key - S3 object key
|
||||
* @param {number} expiresIn - Expiration time in seconds (default 1 hour)
|
||||
* @returns {Promise<string>}
|
||||
*/
|
||||
async getPresignedDownloadUrl(key, expiresIn = 3600) {
|
||||
if (!this.enabled) {
|
||||
throw new Error("S3 storage is not enabled");
|
||||
}
|
||||
|
||||
const command = new GetObjectCommand({
|
||||
Bucket: this.bucket,
|
||||
Key: key,
|
||||
});
|
||||
return getSignedUrl(this.client, command, { expiresIn });
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the public URL for a file (only for public folders)
|
||||
* @param {string} key - S3 object key
|
||||
* @returns {string|null}
|
||||
*/
|
||||
getPublicUrl(key) {
|
||||
if (!this.enabled) {
|
||||
return null;
|
||||
}
|
||||
return `https://${this.bucket}.s3.${this.region}.amazonaws.com/${key}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify that a file exists in S3
|
||||
* @param {string} key - S3 object key
|
||||
* @returns {Promise<boolean>}
|
||||
*/
|
||||
async verifyUpload(key) {
|
||||
if (!this.enabled) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
await this.client.send(
|
||||
new HeadObjectCommand({
|
||||
Bucket: this.bucket,
|
||||
Key: key,
|
||||
})
|
||||
);
|
||||
return true;
|
||||
} catch (err) {
|
||||
if (err.name === "NotFound" || err.$metadata?.httpStatusCode === 404) {
|
||||
return false;
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get file extension from MIME type
|
||||
* @param {string} mime - MIME type
|
||||
* @returns {string}
|
||||
*/
|
||||
getExtFromMime(mime) {
|
||||
const map = {
|
||||
"image/jpeg": ".jpg",
|
||||
"image/jpg": ".jpg",
|
||||
"image/png": ".png",
|
||||
"image/gif": ".gif",
|
||||
"image/webp": ".webp",
|
||||
};
|
||||
return map[mime] || ".jpg";
|
||||
}
|
||||
}
|
||||
|
||||
const s3Service = new S3Service();
|
||||
module.exports = s3Service;
|
||||
Reference in New Issue
Block a user