-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
199 lines (179 loc) · 6 KB
/
index.ts
File metadata and controls
199 lines (179 loc) · 6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
import {
S3Client,
PutObjectCommand,
GetObjectCommand,
PutObjectTaggingCommand,
HeadBucketCommand,
ObjectCannedACL,
GetBucketLifecycleConfigurationCommand,
PutBucketLifecycleConfigurationCommand,
} from "@aws-sdk/client-s3";
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
import { Readable } from 'stream';
import type { StorageAdapter } from "adminforth";
import { afLogger } from "adminforth";
import type { AdapterOptions } from "./types.js";
const CLEANUP_TAG_KEY = "adminforth-candidate-for-cleanup";
const CLEANUP_RULE_ID = "adminforth-unused-cleaner";
export default class AdminForthAdapterS3Storage implements StorageAdapter {
private s3: S3Client;
private options: AdapterOptions;
constructor(options: AdapterOptions) {
this.options = options;
}
async getUploadSignedUrl(key: string, contentType: string, expiresIn = 3600): Promise<{ uploadUrl: string, uploadExtraParams: Record<string, string> }> {
const tagline = `${CLEANUP_TAG_KEY}=true`;
const command = new PutObjectCommand({
Bucket: this.options.bucket,
ContentType: contentType,
ACL: (this.options.s3ACL || 'private') as ObjectCannedACL,
Key: key,
Tagging: tagline,
});
const uploadUrl = await getSignedUrl(this.s3, command, { expiresIn, unhoistableHeaders: new Set(['x-amz-tagging']) });
return {
uploadUrl,
uploadExtraParams: {
'x-amz-tagging': tagline
}
};
}
async getDownloadUrl(key: string, expiresIn = 3600): Promise<string> {
const command = new GetObjectCommand({
Bucket: this.options.bucket,
Key: key,
});
if (this.options.s3ACL === "public-read") {
return `https://${this.options.bucket}.s3.${this.options.region}.amazonaws.com/${key}`;
}
// If the bucket is private, generate a presigned URL
// that expires in the specified time
// (default is 1 hour)
return await getSignedUrl(this.s3, command, { expiresIn });
}
async markKeyForDeletation(key: string): Promise<void> {
afLogger.error("Method \"markKeyForDeletation\" is deprecated, use markKeyForDeletion instead");
const command = new PutObjectTaggingCommand({
Bucket: this.options.bucket,
Key: key,
Tagging: {
TagSet: [{ Key: CLEANUP_TAG_KEY, Value: "true" }],
},
});
await this.s3.send(command);
}
async markKeyForNotDeletation(key: string): Promise<void> {
afLogger.error("Method \"markKeyForNotDeletation\" is deprecated, use markKeyForNotDeletion instead");
const command = new PutObjectTaggingCommand({
Bucket: this.options.bucket,
Key: key,
Tagging: {
TagSet: [],
},
});
await this.s3.send(command);
}
async markKeyForDeletion(key: string): Promise<void> {
const command = new PutObjectTaggingCommand({
Bucket: this.options.bucket,
Key: key,
Tagging: {
TagSet: [{ Key: CLEANUP_TAG_KEY, Value: "true" }],
},
});
await this.s3.send(command);
}
async markKeyForNotDeletion(key: string): Promise<void> {
const command = new PutObjectTaggingCommand({
Bucket: this.options.bucket,
Key: key,
Tagging: {
TagSet: [],
},
});
await this.s3.send(command);
}
async setupLifecycle(): Promise<void> {
if (!this.options.accessKeyId || !this.options.secretAccessKey) {
throw new Error("Missing AWS credentials in environment variables");
}
this.s3 = new S3Client({
region: this.options.region,
credentials: {
accessKeyId: this.options.accessKeyId,
secretAccessKey: this.options.secretAccessKey,
},
});
try {
await this.s3.send(new HeadBucketCommand({ Bucket: this.options.bucket }));
} catch {
throw new Error(`Bucket "${this.options.bucket}" does not exist`);
}
let ruleExists = false;
try {
const res = await this.s3.send(
new GetBucketLifecycleConfigurationCommand({ Bucket: this.options.bucket })
);
ruleExists = res.Rules?.some((r) => r.ID === CLEANUP_RULE_ID) ?? false;
} catch (e: any) {
if (e.name !== "NoSuchLifecycleConfiguration") {
afLogger.error(`Error checking lifecycle config: ${e}`);
throw e;
}
}
if (!ruleExists) {
await this.s3.send(
new PutBucketLifecycleConfigurationCommand({
Bucket: this.options.bucket,
LifecycleConfiguration: {
Rules: [
{
ID: CLEANUP_RULE_ID,
Status: "Enabled",
Filter: {
Tag: {
Key: CLEANUP_TAG_KEY,
Value: "true",
},
},
Expiration: {
Days: 2,
},
},
],
},
})
);
afLogger.debug(`✅ Lifecycle rule "${CLEANUP_RULE_ID}" created.`);
} else {
afLogger.debug(`ℹ️ Lifecycle rule "${CLEANUP_RULE_ID}" already exists.`);
}
}
objectCanBeAccesedPublicly(): Promise<boolean> {
return Promise.resolve(this.options.s3ACL === "public-read");
}
/**
* This method should return the key as a data URL (base64 encoded string).
* @param key - The key of the file to be converted to a data URL
* @returns A promise that resolves to a string containing the data URL
*/
async getKeyAsDataURL(key: string): Promise<string> {
const command = new GetObjectCommand({
Bucket: this.options.bucket,
Key: key,
});
const body = await this.s3.send(command);
const stream = body.Body;
if (!(stream instanceof Readable)) {
throw new Error("Expected Body to be a Readable stream");
}
const chunks: Buffer[] = [];
for await (const chunk of stream) {
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
}
const buffer = Buffer.concat(chunks);
const base64String = buffer.toString('base64');
const contentType = body.ContentType || 'application/octet-stream';
return `data:${contentType};base64,${base64String}`;
}
}