@aglyn/tenant-data-admin 1.0.0-beta.288 → 1.0.0-beta.290
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/package.json +7 -7
- package/src/lib/server/account-acquisition.js +19 -3
- package/src/lib/server/account-acquisition.js.map +1 -1
- package/src/lib/server/platform-marketing-consent.d.ts +33 -0
- package/src/lib/server/platform-marketing-consent.js +58 -0
- package/src/lib/server/platform-marketing-consent.js.map +1 -1
- package/src/lib/server/platform-served-domain.d.ts +60 -0
- package/src/lib/server/platform-served-domain.js +146 -0
- package/src/lib/server/platform-served-domain.js.map +1 -0
- package/src/lib/server/site-preview-token.d.ts +42 -0
- package/src/lib/server/site-preview-token.js +123 -0
- package/src/lib/server/site-preview-token.js.map +1 -0
- package/src/lib/server/site-view-authz.d.ts +88 -0
- package/src/lib/server/site-view-authz.js +103 -0
- package/src/lib/server/site-view-authz.js.map +1 -0
- package/src/lib/server/visitor-upload.d.ts +167 -0
- package/src/lib/server/visitor-upload.js +364 -0
- package/src/lib/server/visitor-upload.js.map +1 -0
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* Copyright 2026 Aglyn LLC
|
|
4
|
+
*
|
|
5
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
* you may not use this file except in compliance with the License.
|
|
7
|
+
* You may obtain a copy of the License at
|
|
8
|
+
*
|
|
9
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
*
|
|
11
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
* See the License for the specific language governing permissions and
|
|
15
|
+
* limitations under the License.
|
|
16
|
+
*/
|
|
17
|
+
import type { Writable } from 'node:stream';
|
|
18
|
+
import { type VisitorUploadFile, type VisitorUploadScope } from '@aglyn/aglyn/app-utils/visitor-upload';
|
|
19
|
+
/** The few Storage calls this makes, so a spec can stand in for the bucket. */
|
|
20
|
+
export interface VisitorUploadObject {
|
|
21
|
+
generateSignedPostPolicyV4(options: {
|
|
22
|
+
expires: number;
|
|
23
|
+
conditions?: unknown[];
|
|
24
|
+
fields?: Record<string, string>;
|
|
25
|
+
}): Promise<[{
|
|
26
|
+
url: string;
|
|
27
|
+
fields: Record<string, string>;
|
|
28
|
+
}] | Array<{
|
|
29
|
+
url: string;
|
|
30
|
+
fields: Record<string, string>;
|
|
31
|
+
}>>;
|
|
32
|
+
exists(): Promise<[boolean] | boolean[]>;
|
|
33
|
+
getMetadata(): Promise<[VisitorUploadObjectMetadata] | VisitorUploadObjectMetadata[]>;
|
|
34
|
+
download(options?: {
|
|
35
|
+
start?: number;
|
|
36
|
+
end?: number;
|
|
37
|
+
}): Promise<[Buffer] | Buffer[]>;
|
|
38
|
+
save(data: Buffer, options: Record<string, unknown>): Promise<unknown>;
|
|
39
|
+
move(destination: string): Promise<unknown>;
|
|
40
|
+
setMetadata(metadata: Record<string, unknown>): Promise<unknown>;
|
|
41
|
+
delete(options?: {
|
|
42
|
+
ignoreNotFound?: boolean;
|
|
43
|
+
}): Promise<unknown>;
|
|
44
|
+
createReadStream(): NodeJS.ReadableStream;
|
|
45
|
+
}
|
|
46
|
+
export interface VisitorUploadObjectMetadata {
|
|
47
|
+
size?: string | number;
|
|
48
|
+
contentType?: string;
|
|
49
|
+
metadata?: Record<string, string | null | undefined> | null;
|
|
50
|
+
}
|
|
51
|
+
export interface VisitorUploadBucket {
|
|
52
|
+
file(path: string): VisitorUploadObject;
|
|
53
|
+
deleteFiles(options: {
|
|
54
|
+
prefix: string;
|
|
55
|
+
}): Promise<unknown>;
|
|
56
|
+
}
|
|
57
|
+
export interface VisitorUploadDeps {
|
|
58
|
+
bucket(): VisitorUploadBucket;
|
|
59
|
+
consumeRateLimit(key: string, options: {
|
|
60
|
+
limit: number;
|
|
61
|
+
windowMs: number;
|
|
62
|
+
}): Promise<{
|
|
63
|
+
allowed: boolean;
|
|
64
|
+
resetMs: number;
|
|
65
|
+
}>;
|
|
66
|
+
/** Whether the platform's uploads pause (`uploads` lockdown feature) is on. */
|
|
67
|
+
uploadsPaused(): Promise<boolean>;
|
|
68
|
+
/** The secret tickets are signed with. Throws when none is configured. */
|
|
69
|
+
secret(): string;
|
|
70
|
+
now(): number;
|
|
71
|
+
/** A fresh upload id: a path segment no one can guess. */
|
|
72
|
+
newId(): string;
|
|
73
|
+
}
|
|
74
|
+
export declare function defaultVisitorUploadDeps(): VisitorUploadDeps;
|
|
75
|
+
/** One rate limit: so many in so long. */
|
|
76
|
+
export interface VisitorUploadRate {
|
|
77
|
+
limit: number;
|
|
78
|
+
windowMs: number;
|
|
79
|
+
}
|
|
80
|
+
/** The limits a ticket spends, per caller on a site and per site. */
|
|
81
|
+
export interface VisitorUploadLimits {
|
|
82
|
+
perCaller: VisitorUploadRate;
|
|
83
|
+
perSite: VisitorUploadRate;
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Tickets per caller on one site: 30 in ten minutes is three full
|
|
87
|
+
* submissions of ten files; per site, 300 an hour across everyone.
|
|
88
|
+
*/
|
|
89
|
+
export declare const VISITOR_UPLOAD_LIMITS: VisitorUploadLimits;
|
|
90
|
+
/** Finalizes per caller on one site, per ten minutes: a retry or two per ticket. */
|
|
91
|
+
export declare const VISITOR_UPLOAD_FINALIZE_LIMIT: VisitorUploadRate;
|
|
92
|
+
/** How long after its upload lapses a ticket may still be finalized: a slow connection's last bytes. */
|
|
93
|
+
export declare const VISITOR_UPLOAD_FINALIZE_GRACE_MS: number;
|
|
94
|
+
/** Who is uploading: an address for a visitor, a uid for a member. Keys the per-caller limit. */
|
|
95
|
+
export type VisitorUploadCaller = {
|
|
96
|
+
ip: string;
|
|
97
|
+
} | {
|
|
98
|
+
uid: string;
|
|
99
|
+
};
|
|
100
|
+
export type VisitorUploadRefusal = {
|
|
101
|
+
ok: false;
|
|
102
|
+
status: number;
|
|
103
|
+
error: string;
|
|
104
|
+
code: 'type' | 'size' | 'empty' | 'scope' | 'rate' | 'paused' | 'ticket' | 'missing' | 'inspection' | 'unchecked';
|
|
105
|
+
retryAfterSeconds?: number;
|
|
106
|
+
};
|
|
107
|
+
export interface VisitorUploadTicket {
|
|
108
|
+
ok: true;
|
|
109
|
+
/** Handed back to finalize. */
|
|
110
|
+
ticket: string;
|
|
111
|
+
/** The signed form post: where, and the fields that go before the file. */
|
|
112
|
+
upload: {
|
|
113
|
+
url: string;
|
|
114
|
+
fields: Record<string, string>;
|
|
115
|
+
};
|
|
116
|
+
/** The file as it will be kept. */
|
|
117
|
+
file: {
|
|
118
|
+
id: string;
|
|
119
|
+
name: string;
|
|
120
|
+
contentType: string;
|
|
121
|
+
size: number;
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* A ticket and a signed upload for ONE file, after the caller's route has
|
|
126
|
+
* decided the caller may upload for `scope`. Spends the rate limits; refused
|
|
127
|
+
* while the platform's uploads are paused. `maxBytes` narrows the 25 MB
|
|
128
|
+
* ceiling, never widens it.
|
|
129
|
+
*/
|
|
130
|
+
export declare function mintVisitorUploadTicket(deps: VisitorUploadDeps, input: {
|
|
131
|
+
scope: VisitorUploadScope;
|
|
132
|
+
request: unknown;
|
|
133
|
+
caller: VisitorUploadCaller;
|
|
134
|
+
limits?: VisitorUploadLimits;
|
|
135
|
+
maxBytes?: number;
|
|
136
|
+
}): Promise<VisitorUploadTicket | VisitorUploadRefusal>;
|
|
137
|
+
/**
|
|
138
|
+
* Checks and keeps the file a ticket signed for. The ticket must be one this
|
|
139
|
+
* signed, for this `scope`, not long lapsed. Idempotent: a retried finalize
|
|
140
|
+
* of a file already kept answers its record.
|
|
141
|
+
*/
|
|
142
|
+
export declare function finalizeVisitorUpload(deps: VisitorUploadDeps, input: {
|
|
143
|
+
scope: VisitorUploadScope;
|
|
144
|
+
ticket: unknown;
|
|
145
|
+
caller: VisitorUploadCaller;
|
|
146
|
+
}): Promise<{
|
|
147
|
+
ok: true;
|
|
148
|
+
file: VisitorUploadFile;
|
|
149
|
+
} | VisitorUploadRefusal>;
|
|
150
|
+
/** A kept file's record, by its id within `scope`; null when there is none. */
|
|
151
|
+
export declare function readVisitorUpload(deps: Pick<VisitorUploadDeps, 'bucket'>, scope: VisitorUploadScope, id: string): Promise<VisitorUploadFile | null>;
|
|
152
|
+
/** Deletes one kept file. Gone already is fine. */
|
|
153
|
+
export declare function deleteVisitorUpload(deps: Pick<VisitorUploadDeps, 'bucket'>, path: string): Promise<void>;
|
|
154
|
+
/** Deletes every kept file of one purpose and record. */
|
|
155
|
+
export declare function deleteVisitorUploads(deps: Pick<VisitorUploadDeps, 'bucket'>, scope: VisitorUploadScope): Promise<void>;
|
|
156
|
+
/** The headers a kept file is served with. */
|
|
157
|
+
export declare function visitorUploadResponseHeaders(file: Pick<VisitorUploadFile, 'name' | 'contentType'>): Record<string, string>;
|
|
158
|
+
/** The response a gated route streams a kept file into. */
|
|
159
|
+
export interface VisitorUploadResponse extends Writable {
|
|
160
|
+
setHeader(name: string, value: string): void;
|
|
161
|
+
status(code: number): unknown;
|
|
162
|
+
}
|
|
163
|
+
/**
|
|
164
|
+
* Streams a kept file to a route's response, after the route has checked the
|
|
165
|
+
* caller. The file is never held whole in memory.
|
|
166
|
+
*/
|
|
167
|
+
export declare function sendVisitorUploadFile(deps: Pick<VisitorUploadDeps, 'bucket'>, res: VisitorUploadResponse, file: Pick<VisitorUploadFile, 'path' | 'name' | 'contentType'>): Promise<void>;
|
|
@@ -0,0 +1,364 @@
|
|
|
1
|
+
import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
2
|
+
/**
|
|
3
|
+
* @license
|
|
4
|
+
* Copyright 2026 Aglyn LLC
|
|
5
|
+
*
|
|
6
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
7
|
+
* you may not use this file except in compliance with the License.
|
|
8
|
+
* You may obtain a copy of the License at
|
|
9
|
+
*
|
|
10
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
11
|
+
*
|
|
12
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
13
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
14
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
15
|
+
* See the License for the specific language governing permissions and
|
|
16
|
+
* limitations under the License.
|
|
17
|
+
*/ import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
|
|
18
|
+
import { pipeline } from "node:stream/promises";
|
|
19
|
+
import { inspectUploadBytes, UPLOAD_INSPECTION_HEAD_BYTES } from "@aglyn/aglyn/app-utils/upload-inspection";
|
|
20
|
+
import { isSvgUploadType, sanitizeSvgBuffer } from "@aglyn/aglyn/app-utils/sanitize-svg";
|
|
21
|
+
import { checkVisitorUploadRequest, isVisitorUploadScope, isVisitorUploadSegment, visitorUploadFinalPath, visitorUploadFolder, visitorUploadIsInline, visitorUploadPendingPath, visitorUploadTypeOf, VISITOR_UPLOAD_MAX_BYTES, VISITOR_UPLOAD_TICKET_TTL_MS } from "@aglyn/aglyn/app-utils/visitor-upload";
|
|
22
|
+
import firebaseAdmin from "./firebase-admin.js";
|
|
23
|
+
import { featureLockdownRefusal } from "./lockdown.js";
|
|
24
|
+
import { consumeRateLimit } from "./rate-limit-store.js";
|
|
25
|
+
export function defaultVisitorUploadDeps() {
|
|
26
|
+
return {
|
|
27
|
+
// The bucket the site's `connect-src` admits by name (`security-origins.js`,
|
|
28
|
+
// `visitorUploadConnectSource`), so the browser's post is allowed to leave.
|
|
29
|
+
bucket: ()=>firebaseAdmin.app().storage().bucket(process.env['NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET'] || undefined),
|
|
30
|
+
consumeRateLimit: (key, options)=>consumeRateLimit(key, options),
|
|
31
|
+
uploadsPaused: async ()=>await featureLockdownRefusal({
|
|
32
|
+
feature: 'uploads'
|
|
33
|
+
}) !== null,
|
|
34
|
+
secret: ()=>{
|
|
35
|
+
const secret = process.env['TOKEN_SIGNING_SECRET'];
|
|
36
|
+
if (!secret) throw new Error('TOKEN_SIGNING_SECRET is not configured');
|
|
37
|
+
return secret;
|
|
38
|
+
},
|
|
39
|
+
now: ()=>Date.now(),
|
|
40
|
+
newId: ()=>randomBytes(12).toString('hex')
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Tickets per caller on one site: 30 in ten minutes is three full
|
|
45
|
+
* submissions of ten files; per site, 300 an hour across everyone.
|
|
46
|
+
*/ export const VISITOR_UPLOAD_LIMITS = {
|
|
47
|
+
perCaller: {
|
|
48
|
+
limit: 30,
|
|
49
|
+
windowMs: 10 * 60000
|
|
50
|
+
},
|
|
51
|
+
perSite: {
|
|
52
|
+
limit: 300,
|
|
53
|
+
windowMs: 60 * 60000
|
|
54
|
+
}
|
|
55
|
+
};
|
|
56
|
+
/** Finalizes per caller on one site, per ten minutes: a retry or two per ticket. */ export const VISITOR_UPLOAD_FINALIZE_LIMIT = {
|
|
57
|
+
limit: 60,
|
|
58
|
+
windowMs: 10 * 60000
|
|
59
|
+
};
|
|
60
|
+
/** How long after its upload lapses a ticket may still be finalized: a slow connection's last bytes. */ export const VISITOR_UPLOAD_FINALIZE_GRACE_MS = 60 * 60000;
|
|
61
|
+
const refusal = (status, code, error, extra = {})=>_extends({
|
|
62
|
+
ok: false,
|
|
63
|
+
status,
|
|
64
|
+
code,
|
|
65
|
+
error
|
|
66
|
+
}, extra);
|
|
67
|
+
const callerKey = (caller)=>'uid' in caller ? `uid:${caller.uid}` : `ip:${caller.ip || 'no-address'}`;
|
|
68
|
+
function signTicket(secret, payload) {
|
|
69
|
+
return createHmac('sha256', secret).update(`visitor-upload:${payload}`).digest('base64url');
|
|
70
|
+
}
|
|
71
|
+
function mintTicket(secret, payload) {
|
|
72
|
+
const encoded = Buffer.from(JSON.stringify(payload), 'utf8').toString('base64url');
|
|
73
|
+
return `${encoded}.${signTicket(secret, encoded)}`;
|
|
74
|
+
}
|
|
75
|
+
/** A ticket's payload when its signature holds, else null. Expiry is the caller's to judge. */ function readTicket(secret, ticket) {
|
|
76
|
+
if (typeof ticket !== 'string' || ticket.length > 2000) return null;
|
|
77
|
+
const separator = ticket.lastIndexOf('.');
|
|
78
|
+
if (separator <= 0) return null;
|
|
79
|
+
const encoded = ticket.slice(0, separator);
|
|
80
|
+
const presented = Buffer.from(ticket.slice(separator + 1));
|
|
81
|
+
const expected = Buffer.from(signTicket(secret, encoded));
|
|
82
|
+
if (presented.length !== expected.length || !timingSafeEqual(presented, expected)) return null;
|
|
83
|
+
try {
|
|
84
|
+
const payload = JSON.parse(Buffer.from(encoded, 'base64url').toString('utf8'));
|
|
85
|
+
if (!isVisitorUploadScope({
|
|
86
|
+
hostId: payload.h,
|
|
87
|
+
purpose: payload.p,
|
|
88
|
+
purposeId: payload.i
|
|
89
|
+
}) || !isVisitorUploadSegment(payload.u) || !visitorUploadTypeOf(String(payload.t)) || !Number.isSafeInteger(payload.s) || typeof payload.n !== 'string' || !Number.isSafeInteger(payload.e)) {
|
|
90
|
+
return null;
|
|
91
|
+
}
|
|
92
|
+
return payload;
|
|
93
|
+
} catch (unused) {
|
|
94
|
+
return null;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* A ticket and a signed upload for ONE file, after the caller's route has
|
|
99
|
+
* decided the caller may upload for `scope`. Spends the rate limits; refused
|
|
100
|
+
* while the platform's uploads are paused. `maxBytes` narrows the 25 MB
|
|
101
|
+
* ceiling, never widens it.
|
|
102
|
+
*/ export async function mintVisitorUploadTicket(deps, input) {
|
|
103
|
+
var _input_limits;
|
|
104
|
+
const { scope } = input;
|
|
105
|
+
if (!isVisitorUploadScope(scope)) return refusal(400, 'scope', 'This upload is missing what it is for.');
|
|
106
|
+
const checked = checkVisitorUploadRequest(input.request, {
|
|
107
|
+
maxBytes: input.maxBytes
|
|
108
|
+
});
|
|
109
|
+
if ('error' in checked) return refusal(checked.code === 'size' ? 413 : 400, checked.code, checked.error);
|
|
110
|
+
if (await deps.uploadsPaused()) {
|
|
111
|
+
return refusal(423, 'paused', 'Uploads are paused for a moment. Try again a little later.');
|
|
112
|
+
}
|
|
113
|
+
const limits = (_input_limits = input.limits) != null ? _input_limits : VISITOR_UPLOAD_LIMITS;
|
|
114
|
+
for (const [key, rate] of [
|
|
115
|
+
[
|
|
116
|
+
`visitor-upload:${scope.hostId}:${callerKey(input.caller)}`,
|
|
117
|
+
limits.perCaller
|
|
118
|
+
],
|
|
119
|
+
[
|
|
120
|
+
`visitor-upload-site:${scope.hostId}`,
|
|
121
|
+
limits.perSite
|
|
122
|
+
]
|
|
123
|
+
]){
|
|
124
|
+
const spent = await deps.consumeRateLimit(key, rate);
|
|
125
|
+
if (!spent.allowed) {
|
|
126
|
+
return refusal(429, 'rate', 'Too many files at once. Wait a few minutes and try again.', {
|
|
127
|
+
retryAfterSeconds: Math.max(1, Math.ceil((spent.resetMs - deps.now()) / 1000))
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
const { upload } = checked;
|
|
132
|
+
const id = deps.newId();
|
|
133
|
+
const expiresAtMs = deps.now() + VISITOR_UPLOAD_TICKET_TTL_MS;
|
|
134
|
+
const answer = await deps.bucket().file(visitorUploadPendingPath(scope, id)).generateSignedPostPolicyV4({
|
|
135
|
+
expires: expiresAtMs,
|
|
136
|
+
// Storage refuses a post of any other size, type or object: each
|
|
137
|
+
// field below is also an exact-match condition of the policy.
|
|
138
|
+
conditions: [
|
|
139
|
+
[
|
|
140
|
+
'content-length-range',
|
|
141
|
+
1,
|
|
142
|
+
upload.size
|
|
143
|
+
]
|
|
144
|
+
],
|
|
145
|
+
fields: {
|
|
146
|
+
'Content-Type': upload.type.contentType
|
|
147
|
+
}
|
|
148
|
+
});
|
|
149
|
+
const signed = answer[0];
|
|
150
|
+
return {
|
|
151
|
+
ok: true,
|
|
152
|
+
ticket: mintTicket(deps.secret(), {
|
|
153
|
+
h: scope.hostId,
|
|
154
|
+
p: scope.purpose,
|
|
155
|
+
i: scope.purposeId,
|
|
156
|
+
u: id,
|
|
157
|
+
t: upload.type.contentType,
|
|
158
|
+
s: upload.size,
|
|
159
|
+
n: upload.name,
|
|
160
|
+
e: expiresAtMs
|
|
161
|
+
}),
|
|
162
|
+
upload: {
|
|
163
|
+
url: signed.url,
|
|
164
|
+
fields: signed.fields
|
|
165
|
+
},
|
|
166
|
+
file: {
|
|
167
|
+
id,
|
|
168
|
+
name: upload.name,
|
|
169
|
+
contentType: upload.type.contentType,
|
|
170
|
+
size: upload.size
|
|
171
|
+
}
|
|
172
|
+
};
|
|
173
|
+
}
|
|
174
|
+
/*------------------------------------------
|
|
175
|
+
* Finalize
|
|
176
|
+
*-----------------------------------------*/ const first = (answer)=>answer[0];
|
|
177
|
+
/** The custom metadata a kept file carries, which is how its record is read back. */ function keptMetadata(name, uploadedAtMs) {
|
|
178
|
+
return {
|
|
179
|
+
name,
|
|
180
|
+
uploadedAtMs: String(uploadedAtMs),
|
|
181
|
+
// Never a download token: nothing but the Admin SDK reads the object.
|
|
182
|
+
firebaseStorageDownloadTokens: null
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
/** A kept file's record from its object's metadata, or null when it is not one. */ function recordFromMetadata(path, id, metadata) {
|
|
186
|
+
var _metadata_contentType, _ref;
|
|
187
|
+
var _metadata_metadata, _metadata_metadata1;
|
|
188
|
+
const contentType = String((_metadata_contentType = metadata.contentType) != null ? _metadata_contentType : '');
|
|
189
|
+
const size = Number(metadata.size);
|
|
190
|
+
const name = String((_ref = (_metadata_metadata = metadata.metadata) == null ? void 0 : _metadata_metadata['name']) != null ? _ref : '');
|
|
191
|
+
if (!visitorUploadTypeOf(contentType) || !Number.isSafeInteger(size) || size <= 0 || !name) return null;
|
|
192
|
+
return {
|
|
193
|
+
id,
|
|
194
|
+
name,
|
|
195
|
+
contentType,
|
|
196
|
+
size,
|
|
197
|
+
path,
|
|
198
|
+
uploadedAtMs: Number((_metadata_metadata1 = metadata.metadata) == null ? void 0 : _metadata_metadata1['uploadedAtMs']) || 0
|
|
199
|
+
};
|
|
200
|
+
}
|
|
201
|
+
/**
|
|
202
|
+
* Checks and keeps the file a ticket signed for. The ticket must be one this
|
|
203
|
+
* signed, for this `scope`, not long lapsed. Idempotent: a retried finalize
|
|
204
|
+
* of a file already kept answers its record.
|
|
205
|
+
*/ export async function finalizeVisitorUpload(deps, input) {
|
|
206
|
+
var _metadata_contentType;
|
|
207
|
+
const { scope } = input;
|
|
208
|
+
if (!isVisitorUploadScope(scope)) return refusal(400, 'scope', 'This upload is missing what it is for.');
|
|
209
|
+
const spent = await deps.consumeRateLimit(`visitor-upload-finalize:${scope.hostId}:${callerKey(input.caller)}`, VISITOR_UPLOAD_FINALIZE_LIMIT);
|
|
210
|
+
if (!spent.allowed) {
|
|
211
|
+
return refusal(429, 'rate', 'Too many files at once. Wait a few minutes and try again.', {
|
|
212
|
+
retryAfterSeconds: Math.max(1, Math.ceil((spent.resetMs - deps.now()) / 1000))
|
|
213
|
+
});
|
|
214
|
+
}
|
|
215
|
+
const ticket = readTicket(deps.secret(), input.ticket);
|
|
216
|
+
const lapsed = 'This upload took too long. Send the file again.';
|
|
217
|
+
if (!ticket || ticket.h !== scope.hostId || ticket.p !== scope.purpose || ticket.i !== scope.purposeId) {
|
|
218
|
+
return refusal(400, 'ticket', lapsed);
|
|
219
|
+
}
|
|
220
|
+
if (deps.now() > ticket.e + VISITOR_UPLOAD_FINALIZE_GRACE_MS) return refusal(410, 'ticket', lapsed);
|
|
221
|
+
const bucket = deps.bucket();
|
|
222
|
+
const finalPath = visitorUploadFinalPath(scope, ticket.u);
|
|
223
|
+
const kept = bucket.file(finalPath);
|
|
224
|
+
if (first(await kept.exists())) {
|
|
225
|
+
const record = recordFromMetadata(finalPath, ticket.u, first(await kept.getMetadata()));
|
|
226
|
+
if (record) return {
|
|
227
|
+
ok: true,
|
|
228
|
+
file: record
|
|
229
|
+
};
|
|
230
|
+
}
|
|
231
|
+
const pending = bucket.file(visitorUploadPendingPath(scope, ticket.u));
|
|
232
|
+
if (!first(await pending.exists())) {
|
|
233
|
+
return refusal(409, 'missing', `We didn’t receive ${ticket.n}. Try sending it again.`);
|
|
234
|
+
}
|
|
235
|
+
const discard = async (answer)=>{
|
|
236
|
+
await pending.delete({
|
|
237
|
+
ignoreNotFound: true
|
|
238
|
+
}).catch(()=>undefined);
|
|
239
|
+
return answer;
|
|
240
|
+
};
|
|
241
|
+
const metadata = first(await pending.getMetadata());
|
|
242
|
+
const size = Number(metadata.size);
|
|
243
|
+
const contentType = String((_metadata_contentType = metadata.contentType) != null ? _metadata_contentType : '');
|
|
244
|
+
if (contentType !== ticket.t) {
|
|
245
|
+
return discard(refusal(415, 'type', `${ticket.n} arrived as a different kind of file. Send it again.`));
|
|
246
|
+
}
|
|
247
|
+
if (!Number.isSafeInteger(size) || size <= 0) return discard(refusal(400, 'empty', `${ticket.n} is empty.`));
|
|
248
|
+
if (size > ticket.s || size > VISITOR_UPLOAD_MAX_BYTES) {
|
|
249
|
+
return discard(refusal(413, 'size', `${ticket.n} is larger than it said it was. Send it again.`));
|
|
250
|
+
}
|
|
251
|
+
// The bytes against the type: a few KB from the front, or all of an SVG,
|
|
252
|
+
// which is text and is stripped of script below. Unlike the console's
|
|
253
|
+
// media route this fails CLOSED: a visitor's file that could not be looked
|
|
254
|
+
// at is not kept.
|
|
255
|
+
let bytes;
|
|
256
|
+
try {
|
|
257
|
+
bytes = isSvgUploadType(contentType) ? first(await pending.download()) : first(await pending.download({
|
|
258
|
+
start: 0,
|
|
259
|
+
end: Math.min(size, UPLOAD_INSPECTION_HEAD_BYTES) - 1
|
|
260
|
+
}));
|
|
261
|
+
} catch (unused) {
|
|
262
|
+
return discard(refusal(503, 'unchecked', `${ticket.n} could not be checked. Send it again.`));
|
|
263
|
+
}
|
|
264
|
+
const inspected = inspectUploadBytes({
|
|
265
|
+
bytes,
|
|
266
|
+
contentType,
|
|
267
|
+
fileName: ticket.n
|
|
268
|
+
});
|
|
269
|
+
if (inspected) return discard(refusal(415, 'inspection', inspected.message));
|
|
270
|
+
const uploadedAtMs = deps.now();
|
|
271
|
+
const disposition = contentDisposition(ticket.n, contentType);
|
|
272
|
+
if (isSvgUploadType(contentType)) {
|
|
273
|
+
const sanitized = sanitizeSvgBuffer(bytes);
|
|
274
|
+
await kept.save(sanitized.buffer, {
|
|
275
|
+
resumable: false,
|
|
276
|
+
contentType,
|
|
277
|
+
metadata: {
|
|
278
|
+
cacheControl: 'private, no-store',
|
|
279
|
+
contentDisposition: disposition,
|
|
280
|
+
metadata: keptMetadata(ticket.n, uploadedAtMs)
|
|
281
|
+
}
|
|
282
|
+
});
|
|
283
|
+
await pending.delete({
|
|
284
|
+
ignoreNotFound: true
|
|
285
|
+
}).catch(()=>undefined);
|
|
286
|
+
return {
|
|
287
|
+
ok: true,
|
|
288
|
+
file: {
|
|
289
|
+
id: ticket.u,
|
|
290
|
+
name: ticket.n,
|
|
291
|
+
contentType,
|
|
292
|
+
size: sanitized.buffer.length,
|
|
293
|
+
path: finalPath,
|
|
294
|
+
uploadedAtMs
|
|
295
|
+
}
|
|
296
|
+
};
|
|
297
|
+
}
|
|
298
|
+
await pending.move(finalPath);
|
|
299
|
+
await kept.setMetadata({
|
|
300
|
+
cacheControl: 'private, no-store',
|
|
301
|
+
contentDisposition: disposition,
|
|
302
|
+
metadata: keptMetadata(ticket.n, uploadedAtMs)
|
|
303
|
+
});
|
|
304
|
+
return {
|
|
305
|
+
ok: true,
|
|
306
|
+
file: {
|
|
307
|
+
id: ticket.u,
|
|
308
|
+
name: ticket.n,
|
|
309
|
+
contentType,
|
|
310
|
+
size,
|
|
311
|
+
path: finalPath,
|
|
312
|
+
uploadedAtMs
|
|
313
|
+
}
|
|
314
|
+
};
|
|
315
|
+
}
|
|
316
|
+
/*------------------------------------------
|
|
317
|
+
* Afterwards
|
|
318
|
+
*-----------------------------------------*/ /** A kept file's record, by its id within `scope`; null when there is none. */ export async function readVisitorUpload(deps, scope, id) {
|
|
319
|
+
if (!isVisitorUploadScope(scope) || !isVisitorUploadSegment(id)) return null;
|
|
320
|
+
const path = visitorUploadFinalPath(scope, id);
|
|
321
|
+
const file = deps.bucket().file(path);
|
|
322
|
+
if (!first(await file.exists())) return null;
|
|
323
|
+
return recordFromMetadata(path, id, first(await file.getMetadata()));
|
|
324
|
+
}
|
|
325
|
+
/** Deletes one kept file. Gone already is fine. */ export async function deleteVisitorUpload(deps, path) {
|
|
326
|
+
if (!path.startsWith('hosts/') || !path.includes('/private/uploads/')) return;
|
|
327
|
+
await deps.bucket().file(path).delete({
|
|
328
|
+
ignoreNotFound: true
|
|
329
|
+
});
|
|
330
|
+
}
|
|
331
|
+
/** Deletes every kept file of one purpose and record. */ export async function deleteVisitorUploads(deps, scope) {
|
|
332
|
+
if (!isVisitorUploadScope(scope)) return;
|
|
333
|
+
await deps.bucket().deleteFiles({
|
|
334
|
+
prefix: visitorUploadFolder(scope)
|
|
335
|
+
});
|
|
336
|
+
}
|
|
337
|
+
/** An ASCII stand-in for a header, and the real name encoded beside it. */ function contentDisposition(name, contentType) {
|
|
338
|
+
const ascii = name.replace(/[^\x20-\x7e]/g, '_').replace(/["\\]/g, '_') || 'file';
|
|
339
|
+
const kind = visitorUploadIsInline(contentType) ? 'inline' : 'attachment';
|
|
340
|
+
return `${kind}; filename="${ascii}"; filename*=UTF-8''${encodeURIComponent(name)}`;
|
|
341
|
+
}
|
|
342
|
+
/** The headers a kept file is served with. */ export function visitorUploadResponseHeaders(file) {
|
|
343
|
+
return {
|
|
344
|
+
'Content-Type': file.contentType,
|
|
345
|
+
'Content-Disposition': contentDisposition(file.name, file.contentType),
|
|
346
|
+
'X-Content-Type-Options': 'nosniff',
|
|
347
|
+
// Whatever the bytes turn out to be, they run nothing and load nothing.
|
|
348
|
+
'Content-Security-Policy': "default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'; sandbox",
|
|
349
|
+
'Cache-Control': 'private, no-store',
|
|
350
|
+
'X-Robots-Tag': 'noindex, nofollow',
|
|
351
|
+
'Referrer-Policy': 'no-referrer',
|
|
352
|
+
'Cross-Origin-Resource-Policy': 'same-origin'
|
|
353
|
+
};
|
|
354
|
+
}
|
|
355
|
+
/**
|
|
356
|
+
* Streams a kept file to a route's response, after the route has checked the
|
|
357
|
+
* caller. The file is never held whole in memory.
|
|
358
|
+
*/ export async function sendVisitorUploadFile(deps, res, file) {
|
|
359
|
+
for (const [name, value] of Object.entries(visitorUploadResponseHeaders(file)))res.setHeader(name, value);
|
|
360
|
+
res.status(200);
|
|
361
|
+
await pipeline(deps.bucket().file(file.path).createReadStream(), res);
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
//# sourceMappingURL=visitor-upload.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/visitor-upload.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { createHmac, randomBytes, timingSafeEqual } from 'node:crypto'\nimport { pipeline } from 'node:stream/promises'\nimport type { Writable } from 'node:stream'\nimport {\n inspectUploadBytes,\n UPLOAD_INSPECTION_HEAD_BYTES,\n} from '@aglyn/aglyn/app-utils/upload-inspection'\nimport { isSvgUploadType, sanitizeSvgBuffer } from '@aglyn/aglyn/app-utils/sanitize-svg'\nimport {\n checkVisitorUploadRequest,\n isVisitorUploadScope,\n isVisitorUploadSegment,\n visitorUploadFinalPath,\n visitorUploadFolder,\n visitorUploadIsInline,\n visitorUploadPendingPath,\n visitorUploadTypeOf,\n VISITOR_UPLOAD_MAX_BYTES,\n VISITOR_UPLOAD_TICKET_TTL_MS,\n type VisitorUploadFile,\n type VisitorUploadScope,\n} from '@aglyn/aglyn/app-utils/visitor-upload'\nimport firebaseAdmin from './firebase-admin'\nimport { featureLockdownRefusal } from './lockdown'\nimport { consumeRateLimit } from './rate-limit-store'\n\n/*==========================================\n * TAKING A FILE FROM A SITE'S VISITOR, OR A MEMBER (AGL-4096).\n *\n * Two calls a plugin's own routes make, after deciding for themselves who may\n * upload for what (a quote's signed link, a form's binding, a member's key):\n *\n * mintVisitorUploadTicket → a TICKET and a signed upload for one file of a\n * declared name, type and size, to a PENDING\n * path scoped to (site, purpose, record);\n * finalizeVisitorUpload → reads what arrived there, checks its size and\n * bytes (`inspectUploadBytes`), strips script\n * from an SVG, moves it to the record's private\n * folder and answers its {@link VisitorUploadFile}.\n *\n * And three for afterwards: {@link readVisitorUpload} (a kept file's record,\n * by id, so a later submit names files by id and nothing else),\n * {@link sendVisitorUploadFile} (serve one through a gated route) and\n * {@link deleteVisitorUpload} / {@link deleteVisitorUploads}.\n *\n * THE UPLOAD IS A SIGNED POST POLICY, not a signed PUT URL. A site lives on\n * any domain, and the bucket's cross-origin list names the console's\n * addresses one by one and never `*` (AGL-1452), so a browser on a\n * customer's domain could not make the PUT. A form post needs no such\n * permission. The policy binds the exact object, the type and the size range\n * and lapses after {@link VISITOR_UPLOAD_TICKET_TTL_MS}, so Storage itself\n * refuses anything else; finalize then checks again, because the bytes are\n * what matter.\n *\n * THE TICKET is `<payload>.<signature>`: the scope, the upload's id, its\n * type, size and name and when it lapses, HMAC-signed under\n * `TOKEN_SIGNING_SECRET` with a `visitor-upload:` prefix so it cannot be\n * replayed as any other token. Nothing is stored per ticket. It is an\n * internal handle for the seconds between upload and finalize, never a state\n * anyone sees.\n *\n * WHAT IS NEVER FINALIZED is deleted by the bucket's lifecycle a day after it\n * arrived: `visitor-uploads-pending/` in `cloud/media-bucket-lifecycle.json`.\n * A refused finalize deletes its object at once.\n *\n * THE KEPT FILE has no download token and lives under `hosts/{hostId}/private/`,\n * so only the Admin SDK reads it, the site's erasure deletes it with the\n * site, and a route that checked the caller serves it\n * ({@link sendVisitorUploadFile}: `nosniff`, a sandboxing CSP, and\n * `attachment` for everything but the raster images a browser draws safely).\n *\n * Abuse: each ticket spends a per-caller and a per-site rate limit, the\n * platform's uploads pause (`uploads` lockdown feature) refuses new tickets,\n * and the plugin route sits behind the site dispatcher's cross-origin check,\n * lockdown and visitor-write limit.\n *=========================================*/\n\n/** The few Storage calls this makes, so a spec can stand in for the bucket. */\nexport interface VisitorUploadObject {\n generateSignedPostPolicyV4(options: {\n expires: number\n conditions?: unknown[]\n fields?: Record<string, string>\n }): Promise<[{ url: string; fields: Record<string, string> }] | Array<{ url: string; fields: Record<string, string> }>>\n exists(): Promise<[boolean] | boolean[]>\n getMetadata(): Promise<[VisitorUploadObjectMetadata] | VisitorUploadObjectMetadata[]>\n download(options?: { start?: number; end?: number }): Promise<[Buffer] | Buffer[]>\n save(data: Buffer, options: Record<string, unknown>): Promise<unknown>\n move(destination: string): Promise<unknown>\n setMetadata(metadata: Record<string, unknown>): Promise<unknown>\n delete(options?: { ignoreNotFound?: boolean }): Promise<unknown>\n createReadStream(): NodeJS.ReadableStream\n}\n\nexport interface VisitorUploadObjectMetadata {\n size?: string | number\n contentType?: string\n metadata?: Record<string, string | null | undefined> | null\n}\n\nexport interface VisitorUploadBucket {\n file(path: string): VisitorUploadObject\n deleteFiles(options: { prefix: string }): Promise<unknown>\n}\n\nexport interface VisitorUploadDeps {\n bucket(): VisitorUploadBucket\n consumeRateLimit(key: string, options: { limit: number; windowMs: number }): Promise<{ allowed: boolean; resetMs: number }>\n /** Whether the platform's uploads pause (`uploads` lockdown feature) is on. */\n uploadsPaused(): Promise<boolean>\n /** The secret tickets are signed with. Throws when none is configured. */\n secret(): string\n now(): number\n /** A fresh upload id: a path segment no one can guess. */\n newId(): string\n}\n\nexport function defaultVisitorUploadDeps(): VisitorUploadDeps {\n return {\n // The bucket the site's `connect-src` admits by name (`security-origins.js`,\n // `visitorUploadConnectSource`), so the browser's post is allowed to leave.\n bucket: () =>\n firebaseAdmin\n .app()\n .storage()\n .bucket(process.env['NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET'] || undefined) as unknown as VisitorUploadBucket,\n consumeRateLimit: (key, options) => consumeRateLimit(key, options),\n uploadsPaused: async () => (await featureLockdownRefusal({ feature: 'uploads' })) !== null,\n secret: () => {\n const secret = process.env['TOKEN_SIGNING_SECRET']\n if (!secret) throw new Error('TOKEN_SIGNING_SECRET is not configured')\n return secret\n },\n now: () => Date.now(),\n newId: () => randomBytes(12).toString('hex'),\n }\n}\n\n/** One rate limit: so many in so long. */\nexport interface VisitorUploadRate {\n limit: number\n windowMs: number\n}\n\n/** The limits a ticket spends, per caller on a site and per site. */\nexport interface VisitorUploadLimits {\n perCaller: VisitorUploadRate\n perSite: VisitorUploadRate\n}\n\n/**\n * Tickets per caller on one site: 30 in ten minutes is three full\n * submissions of ten files; per site, 300 an hour across everyone.\n */\nexport const VISITOR_UPLOAD_LIMITS: VisitorUploadLimits = {\n perCaller: { limit: 30, windowMs: 10 * 60_000 },\n perSite: { limit: 300, windowMs: 60 * 60_000 },\n}\n\n/** Finalizes per caller on one site, per ten minutes: a retry or two per ticket. */\nexport const VISITOR_UPLOAD_FINALIZE_LIMIT: VisitorUploadRate = { limit: 60, windowMs: 10 * 60_000 }\n\n/** How long after its upload lapses a ticket may still be finalized: a slow connection's last bytes. */\nexport const VISITOR_UPLOAD_FINALIZE_GRACE_MS = 60 * 60_000\n\n/** Who is uploading: an address for a visitor, a uid for a member. Keys the per-caller limit. */\nexport type VisitorUploadCaller = { ip: string } | { uid: string }\n\nexport type VisitorUploadRefusal = {\n ok: false\n status: number\n error: string\n code: 'type' | 'size' | 'empty' | 'scope' | 'rate' | 'paused' | 'ticket' | 'missing' | 'inspection' | 'unchecked'\n retryAfterSeconds?: number\n}\n\nconst refusal = (\n status: number,\n code: VisitorUploadRefusal['code'],\n error: string,\n extra: Partial<VisitorUploadRefusal> = {},\n): VisitorUploadRefusal => ({ ok: false, status, code, error, ...extra })\n\nconst callerKey = (caller: VisitorUploadCaller) => ('uid' in caller ? `uid:${caller.uid}` : `ip:${caller.ip || 'no-address'}`)\n\n/*------------------------------------------\n * The ticket\n *-----------------------------------------*/\n\ninterface TicketPayload {\n h: string\n p: string\n i: string\n u: string\n t: string\n s: number\n n: string\n e: number\n}\n\nfunction signTicket(secret: string, payload: string): string {\n return createHmac('sha256', secret).update(`visitor-upload:${payload}`).digest('base64url')\n}\n\nfunction mintTicket(secret: string, payload: TicketPayload): string {\n const encoded = Buffer.from(JSON.stringify(payload), 'utf8').toString('base64url')\n return `${encoded}.${signTicket(secret, encoded)}`\n}\n\n/** A ticket's payload when its signature holds, else null. Expiry is the caller's to judge. */\nfunction readTicket(secret: string, ticket: unknown): TicketPayload | null {\n if (typeof ticket !== 'string' || ticket.length > 2_000) return null\n const separator = ticket.lastIndexOf('.')\n if (separator <= 0) return null\n const encoded = ticket.slice(0, separator)\n const presented = Buffer.from(ticket.slice(separator + 1))\n const expected = Buffer.from(signTicket(secret, encoded))\n if (presented.length !== expected.length || !timingSafeEqual(presented, expected)) return null\n try {\n const payload = JSON.parse(Buffer.from(encoded, 'base64url').toString('utf8')) as TicketPayload\n if (\n !isVisitorUploadScope({ hostId: payload.h, purpose: payload.p, purposeId: payload.i }) ||\n !isVisitorUploadSegment(payload.u) ||\n !visitorUploadTypeOf(String(payload.t)) ||\n !Number.isSafeInteger(payload.s) ||\n typeof payload.n !== 'string' ||\n !Number.isSafeInteger(payload.e)\n ) {\n return null\n }\n return payload\n } catch {\n return null\n }\n}\n\n/*------------------------------------------\n * Mint\n *-----------------------------------------*/\n\nexport interface VisitorUploadTicket {\n ok: true\n /** Handed back to finalize. */\n ticket: string\n /** The signed form post: where, and the fields that go before the file. */\n upload: { url: string; fields: Record<string, string> }\n /** The file as it will be kept. */\n file: { id: string; name: string; contentType: string; size: number }\n}\n\n/**\n * A ticket and a signed upload for ONE file, after the caller's route has\n * decided the caller may upload for `scope`. Spends the rate limits; refused\n * while the platform's uploads are paused. `maxBytes` narrows the 25 MB\n * ceiling, never widens it.\n */\nexport async function mintVisitorUploadTicket(\n deps: VisitorUploadDeps,\n input: {\n scope: VisitorUploadScope\n request: unknown\n caller: VisitorUploadCaller\n limits?: VisitorUploadLimits\n maxBytes?: number\n },\n): Promise<VisitorUploadTicket | VisitorUploadRefusal> {\n const { scope } = input\n if (!isVisitorUploadScope(scope)) return refusal(400, 'scope', 'This upload is missing what it is for.')\n const checked = checkVisitorUploadRequest(input.request, { maxBytes: input.maxBytes })\n if ('error' in checked) return refusal(checked.code === 'size' ? 413 : 400, checked.code, checked.error)\n if (await deps.uploadsPaused()) {\n return refusal(423, 'paused', 'Uploads are paused for a moment. Try again a little later.')\n }\n const limits = input.limits ?? VISITOR_UPLOAD_LIMITS\n for (const [key, rate] of [\n [`visitor-upload:${scope.hostId}:${callerKey(input.caller)}`, limits.perCaller],\n [`visitor-upload-site:${scope.hostId}`, limits.perSite],\n ] as const) {\n const spent = await deps.consumeRateLimit(key, rate)\n if (!spent.allowed) {\n return refusal(429, 'rate', 'Too many files at once. Wait a few minutes and try again.', {\n retryAfterSeconds: Math.max(1, Math.ceil((spent.resetMs - deps.now()) / 1000)),\n })\n }\n }\n\n const { upload } = checked\n const id = deps.newId()\n const expiresAtMs = deps.now() + VISITOR_UPLOAD_TICKET_TTL_MS\n const answer = await deps\n .bucket()\n .file(visitorUploadPendingPath(scope, id))\n .generateSignedPostPolicyV4({\n expires: expiresAtMs,\n // Storage refuses a post of any other size, type or object: each\n // field below is also an exact-match condition of the policy.\n conditions: [['content-length-range', 1, upload.size]],\n fields: { 'Content-Type': upload.type.contentType },\n })\n const signed = answer[0]\n return {\n ok: true,\n ticket: mintTicket(deps.secret(), {\n h: scope.hostId,\n p: scope.purpose,\n i: scope.purposeId,\n u: id,\n t: upload.type.contentType,\n s: upload.size,\n n: upload.name,\n e: expiresAtMs,\n }),\n upload: { url: signed.url, fields: signed.fields },\n file: { id, name: upload.name, contentType: upload.type.contentType, size: upload.size },\n }\n}\n\n/*------------------------------------------\n * Finalize\n *-----------------------------------------*/\n\nconst first = <T,>(answer: [T] | T[]): T => answer[0] as T\n\n/** The custom metadata a kept file carries, which is how its record is read back. */\nfunction keptMetadata(name: string, uploadedAtMs: number): Record<string, string | null> {\n return {\n name,\n uploadedAtMs: String(uploadedAtMs),\n // Never a download token: nothing but the Admin SDK reads the object.\n firebaseStorageDownloadTokens: null,\n }\n}\n\n/** A kept file's record from its object's metadata, or null when it is not one. */\nfunction recordFromMetadata(path: string, id: string, metadata: VisitorUploadObjectMetadata): VisitorUploadFile | null {\n const contentType = String(metadata.contentType ?? '')\n const size = Number(metadata.size)\n const name = String(metadata.metadata?.['name'] ?? '')\n if (!visitorUploadTypeOf(contentType) || !Number.isSafeInteger(size) || size <= 0 || !name) return null\n return {\n id,\n name,\n contentType,\n size,\n path,\n uploadedAtMs: Number(metadata.metadata?.['uploadedAtMs']) || 0,\n }\n}\n\n/**\n * Checks and keeps the file a ticket signed for. The ticket must be one this\n * signed, for this `scope`, not long lapsed. Idempotent: a retried finalize\n * of a file already kept answers its record.\n */\nexport async function finalizeVisitorUpload(\n deps: VisitorUploadDeps,\n input: { scope: VisitorUploadScope; ticket: unknown; caller: VisitorUploadCaller },\n): Promise<{ ok: true; file: VisitorUploadFile } | VisitorUploadRefusal> {\n const { scope } = input\n if (!isVisitorUploadScope(scope)) return refusal(400, 'scope', 'This upload is missing what it is for.')\n const spent = await deps.consumeRateLimit(\n `visitor-upload-finalize:${scope.hostId}:${callerKey(input.caller)}`,\n VISITOR_UPLOAD_FINALIZE_LIMIT,\n )\n if (!spent.allowed) {\n return refusal(429, 'rate', 'Too many files at once. Wait a few minutes and try again.', {\n retryAfterSeconds: Math.max(1, Math.ceil((spent.resetMs - deps.now()) / 1000)),\n })\n }\n const ticket = readTicket(deps.secret(), input.ticket)\n const lapsed = 'This upload took too long. Send the file again.'\n if (\n !ticket ||\n ticket.h !== scope.hostId ||\n ticket.p !== scope.purpose ||\n ticket.i !== scope.purposeId\n ) {\n return refusal(400, 'ticket', lapsed)\n }\n if (deps.now() > ticket.e + VISITOR_UPLOAD_FINALIZE_GRACE_MS) return refusal(410, 'ticket', lapsed)\n\n const bucket = deps.bucket()\n const finalPath = visitorUploadFinalPath(scope, ticket.u)\n const kept = bucket.file(finalPath)\n if (first(await kept.exists())) {\n const record = recordFromMetadata(finalPath, ticket.u, first(await kept.getMetadata()))\n if (record) return { ok: true, file: record }\n }\n\n const pending = bucket.file(visitorUploadPendingPath(scope, ticket.u))\n if (!first(await pending.exists())) {\n return refusal(409, 'missing', `We didn’t receive ${ticket.n}. Try sending it again.`)\n }\n const discard = async <T,>(answer: T): Promise<T> => {\n await pending.delete({ ignoreNotFound: true }).catch(() => undefined)\n return answer\n }\n const metadata = first(await pending.getMetadata())\n const size = Number(metadata.size)\n const contentType = String(metadata.contentType ?? '')\n if (contentType !== ticket.t) {\n return discard(refusal(415, 'type', `${ticket.n} arrived as a different kind of file. Send it again.`))\n }\n if (!Number.isSafeInteger(size) || size <= 0) return discard(refusal(400, 'empty', `${ticket.n} is empty.`))\n if (size > ticket.s || size > VISITOR_UPLOAD_MAX_BYTES) {\n return discard(refusal(413, 'size', `${ticket.n} is larger than it said it was. Send it again.`))\n }\n\n // The bytes against the type: a few KB from the front, or all of an SVG,\n // which is text and is stripped of script below. Unlike the console's\n // media route this fails CLOSED: a visitor's file that could not be looked\n // at is not kept.\n let bytes: Buffer\n try {\n bytes = isSvgUploadType(contentType)\n ? first(await pending.download())\n : first(await pending.download({ start: 0, end: Math.min(size, UPLOAD_INSPECTION_HEAD_BYTES) - 1 }))\n } catch {\n return discard(refusal(503, 'unchecked', `${ticket.n} could not be checked. Send it again.`))\n }\n const inspected = inspectUploadBytes({ bytes, contentType, fileName: ticket.n })\n if (inspected) return discard(refusal(415, 'inspection', inspected.message))\n\n const uploadedAtMs = deps.now()\n const disposition = contentDisposition(ticket.n, contentType)\n if (isSvgUploadType(contentType)) {\n const sanitized = sanitizeSvgBuffer(bytes)\n await kept.save(sanitized.buffer, {\n resumable: false,\n contentType,\n metadata: {\n cacheControl: 'private, no-store',\n contentDisposition: disposition,\n metadata: keptMetadata(ticket.n, uploadedAtMs),\n },\n })\n await pending.delete({ ignoreNotFound: true }).catch(() => undefined)\n return {\n ok: true,\n file: { id: ticket.u, name: ticket.n, contentType, size: sanitized.buffer.length, path: finalPath, uploadedAtMs },\n }\n }\n await pending.move(finalPath)\n await kept.setMetadata({\n cacheControl: 'private, no-store',\n contentDisposition: disposition,\n metadata: keptMetadata(ticket.n, uploadedAtMs),\n })\n return { ok: true, file: { id: ticket.u, name: ticket.n, contentType, size, path: finalPath, uploadedAtMs } }\n}\n\n/*------------------------------------------\n * Afterwards\n *-----------------------------------------*/\n\n/** A kept file's record, by its id within `scope`; null when there is none. */\nexport async function readVisitorUpload(\n deps: Pick<VisitorUploadDeps, 'bucket'>,\n scope: VisitorUploadScope,\n id: string,\n): Promise<VisitorUploadFile | null> {\n if (!isVisitorUploadScope(scope) || !isVisitorUploadSegment(id)) return null\n const path = visitorUploadFinalPath(scope, id)\n const file = deps.bucket().file(path)\n if (!first(await file.exists())) return null\n return recordFromMetadata(path, id, first(await file.getMetadata()))\n}\n\n/** Deletes one kept file. Gone already is fine. */\nexport async function deleteVisitorUpload(deps: Pick<VisitorUploadDeps, 'bucket'>, path: string): Promise<void> {\n if (!path.startsWith('hosts/') || !path.includes('/private/uploads/')) return\n await deps.bucket().file(path).delete({ ignoreNotFound: true })\n}\n\n/** Deletes every kept file of one purpose and record. */\nexport async function deleteVisitorUploads(deps: Pick<VisitorUploadDeps, 'bucket'>, scope: VisitorUploadScope): Promise<void> {\n if (!isVisitorUploadScope(scope)) return\n await deps.bucket().deleteFiles({ prefix: visitorUploadFolder(scope) })\n}\n\n/** An ASCII stand-in for a header, and the real name encoded beside it. */\nfunction contentDisposition(name: string, contentType: string): string {\n const ascii = name.replace(/[^\\x20-\\x7e]/g, '_').replace(/[\"\\\\]/g, '_') || 'file'\n const kind = visitorUploadIsInline(contentType) ? 'inline' : 'attachment'\n return `${kind}; filename=\"${ascii}\"; filename*=UTF-8''${encodeURIComponent(name)}`\n}\n\n/** The headers a kept file is served with. */\nexport function visitorUploadResponseHeaders(file: Pick<VisitorUploadFile, 'name' | 'contentType'>): Record<string, string> {\n return {\n 'Content-Type': file.contentType,\n 'Content-Disposition': contentDisposition(file.name, file.contentType),\n 'X-Content-Type-Options': 'nosniff',\n // Whatever the bytes turn out to be, they run nothing and load nothing.\n 'Content-Security-Policy': \"default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'; sandbox\",\n 'Cache-Control': 'private, no-store',\n 'X-Robots-Tag': 'noindex, nofollow',\n 'Referrer-Policy': 'no-referrer',\n 'Cross-Origin-Resource-Policy': 'same-origin',\n }\n}\n\n/** The response a gated route streams a kept file into. */\nexport interface VisitorUploadResponse extends Writable {\n setHeader(name: string, value: string): void\n status(code: number): unknown\n}\n\n/**\n * Streams a kept file to a route's response, after the route has checked the\n * caller. The file is never held whole in memory.\n */\nexport async function sendVisitorUploadFile(\n deps: Pick<VisitorUploadDeps, 'bucket'>,\n res: VisitorUploadResponse,\n file: Pick<VisitorUploadFile, 'path' | 'name' | 'contentType'>,\n): Promise<void> {\n for (const [name, value] of Object.entries(visitorUploadResponseHeaders(file))) res.setHeader(name, value)\n res.status(200)\n await pipeline(deps.bucket().file(file.path).createReadStream(), res)\n}\n"],"names":["createHmac","randomBytes","timingSafeEqual","pipeline","inspectUploadBytes","UPLOAD_INSPECTION_HEAD_BYTES","isSvgUploadType","sanitizeSvgBuffer","checkVisitorUploadRequest","isVisitorUploadScope","isVisitorUploadSegment","visitorUploadFinalPath","visitorUploadFolder","visitorUploadIsInline","visitorUploadPendingPath","visitorUploadTypeOf","VISITOR_UPLOAD_MAX_BYTES","VISITOR_UPLOAD_TICKET_TTL_MS","firebaseAdmin","featureLockdownRefusal","consumeRateLimit","defaultVisitorUploadDeps","bucket","app","storage","process","env","undefined","key","options","uploadsPaused","feature","secret","Error","now","Date","newId","toString","VISITOR_UPLOAD_LIMITS","perCaller","limit","windowMs","perSite","VISITOR_UPLOAD_FINALIZE_LIMIT","VISITOR_UPLOAD_FINALIZE_GRACE_MS","refusal","status","code","error","extra","ok","callerKey","caller","uid","ip","signTicket","payload","update","digest","mintTicket","encoded","Buffer","from","JSON","stringify","readTicket","ticket","length","separator","lastIndexOf","slice","presented","expected","parse","hostId","h","purpose","p","purposeId","i","u","String","t","Number","isSafeInteger","s","n","e","mintVisitorUploadTicket","deps","input","scope","checked","request","maxBytes","limits","rate","spent","allowed","retryAfterSeconds","Math","max","ceil","resetMs","upload","id","expiresAtMs","answer","file","generateSignedPostPolicyV4","expires","conditions","size","fields","type","contentType","signed","name","url","first","keptMetadata","uploadedAtMs","firebaseStorageDownloadTokens","recordFromMetadata","path","metadata","finalizeVisitorUpload","lapsed","finalPath","kept","exists","record","getMetadata","pending","discard","delete","ignoreNotFound","catch","bytes","download","start","end","min","inspected","fileName","message","disposition","contentDisposition","sanitized","save","buffer","resumable","cacheControl","move","setMetadata","readVisitorUpload","deleteVisitorUpload","startsWith","includes","deleteVisitorUploads","deleteFiles","prefix","ascii","replace","kind","encodeURIComponent","visitorUploadResponseHeaders","sendVisitorUploadFile","res","value","Object","entries","setHeader","createReadStream"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,UAAU,EAAEC,WAAW,EAAEC,eAAe,QAAQ,cAAa;AACtE,SAASC,QAAQ,QAAQ,uBAAsB;AAE/C,SACEC,kBAAkB,EAClBC,4BAA4B,QACvB,2CAA0C;AACjD,SAASC,eAAe,EAAEC,iBAAiB,QAAQ,sCAAqC;AACxF,SACEC,yBAAyB,EACzBC,oBAAoB,EACpBC,sBAAsB,EACtBC,sBAA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