Files
Jyotisha/frontend/src/lib/avatar-image.ts
T
ClaudeandClaude Fable 5.2 21ff01b283 feat(account): top-up admin switch, faster 账户与点数, user credit ledger API, avatar upload server side (BUG-2057)
- 「充值」 is an admin switch (billing.purchase on the 功能开关 page, off until
  turned on, existing permission and audit). Open = switch on and gateway
  usable; the answer rides on the account payload as paymentOpen. Closed: no
  packages request, no purchase tabs, empty product list, orders refused.
- The billing panel chunk is prefetched while idle and when a settings
  section opens; the packages route reads its three inputs in one round; a
  same-height line holds the place while the list is unknown.
- GET /api/account/credit-ledger: the caller's own rows (read as the user,
  filtered by the session id), 20 per page with a cursor, all/in/out/redeem,
  reader names only, free turns hidden, links only to owned reports/sessions.
- Avatar upload server side: PUT/GET/DELETE /api/account/avatar/image, JPEG
  or WebP, square up to 256, 200 KB, type and size read from the bytes,
  rate-limited; stored in profile_avatar_images (owner-only RLS, migration
  20261120100000); account payload carries only avatarImage.version.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DbBXoyn7Hj3LCW3BUs5bZ8
2026-11-20 10:48:03 +08:00

142 lines
6.3 KiB
TypeScript

/**
* An uploaded account avatar (BUG-2057). The browser crops the picture to a
* square of at most 256 x 256 and sends that small file; the original never
* leaves the device. The server reads the file's own header to learn what it
* is and how large the picture is. It trusts neither the file name nor the
* type the browser reports, and it does not re-encode.
*
* The avatar is shown only to its owner (settings and the sidebar), so nothing
* is reviewed.
*/
/** The hard ceiling for the stored file. A 256 x 256 JPEG or WebP is about 60 KB. */
export const AVATAR_IMAGE_MAX_BYTES = 200 * 1024;
/** The side the browser crops to, and the largest the server accepts. */
export const AVATAR_IMAGE_SIDE = 256;
export const AVATAR_IMAGE_MIN_SIDE = 32;
/** The original picture is checked in the browser before cropping; it is never uploaded. */
export const AVATAR_SOURCE_MAX_BYTES = 5 * 1024 * 1024;
export const AVATAR_IMAGE_PATH = "/api/account/avatar/image";
export type AvatarImageType = "image/jpeg" | "image/webp";
export type AvatarImageErrorCode =
| "AVATAR_IMAGE_EMPTY"
| "AVATAR_TOO_LARGE"
| "AVATAR_TYPE_UNSUPPORTED"
| "AVATAR_IMAGE_INVALID"
| "AVATAR_DIMENSIONS_INVALID";
export type AvatarImageCheck =
| Readonly<{ ok: true; contentType: AvatarImageType; width: number; height: number }>
| Readonly<{ ok: false; code: AvatarImageErrorCode }>;
/** What the account payload carries: that a picture exists and which one, never the bytes. */
export type AvatarImageRef = Readonly<{ version: string }>;
export const AVATAR_IMAGE_ERRORS: Readonly<Record<AvatarImageErrorCode, { status: number; error: string }>> = {
AVATAR_IMAGE_EMPTY: { status: 400, error: "没有收到图片" },
AVATAR_TOO_LARGE: { status: 413, error: "图片太大了" },
AVATAR_TYPE_UNSUPPORTED: { status: 415, error: "只支持 JPG 或 WebP 图片" },
AVATAR_IMAGE_INVALID: { status: 400, error: "这张图片读不出来" },
AVATAR_DIMENSIONS_INVALID: { status: 422, error: "图片尺寸不对" },
};
const ascii = (bytes: Uint8Array, start: number, length: number) =>
String.fromCharCode(...bytes.subarray(start, start + length));
function jpegSize(bytes: Uint8Array): { width: number; height: number } | null {
let offset = 2;
while (offset + 4 <= bytes.length) {
if (bytes[offset] !== 0xff) return null;
const marker = bytes[offset + 1]!;
if (marker === 0xff) { offset += 1; continue; }
// Markers without a length field.
if (marker === 0x01 || (marker >= 0xd0 && marker <= 0xd7)) { offset += 2; continue; }
// End of image or start of scan before any frame header: no size to read.
if (marker === 0xd9 || marker === 0xda) return null;
const length = (bytes[offset + 2]! << 8) | bytes[offset + 3]!;
if (length < 2) return null;
const frameHeader = marker >= 0xc0 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc;
if (frameHeader) {
if (offset + 9 > bytes.length) return null;
return {
height: (bytes[offset + 5]! << 8) | bytes[offset + 6]!,
width: (bytes[offset + 7]! << 8) | bytes[offset + 8]!,
};
}
offset += 2 + length;
}
return null;
}
function webpSize(bytes: Uint8Array): { width: number; height: number } | "animated" | null {
if (bytes.length < 30) return null;
const chunk = ascii(bytes, 12, 4);
if (chunk === "VP8 ") {
// Lossy: a 3-byte frame tag, the start code 9d 01 2a, then 14-bit width and height.
if (bytes[23] !== 0x9d || bytes[24] !== 0x01 || bytes[25] !== 0x2a) return null;
return {
width: (bytes[26]! | (bytes[27]! << 8)) & 0x3fff,
height: (bytes[28]! | (bytes[29]! << 8)) & 0x3fff,
};
}
if (chunk === "VP8L") {
// Lossless: signature 2f, then 14 bits of width-1 and 14 bits of height-1.
if (bytes[20] !== 0x2f) return null;
const bits = bytes[21]! | (bytes[22]! << 8) | (bytes[23]! << 16) | (bytes[24]! << 24);
return { width: (bits & 0x3fff) + 1, height: ((bits >>> 14) & 0x3fff) + 1 };
}
if (chunk === "VP8X") {
// Extended: a flags byte (bit 1 = animation), then 24-bit width-1 and height-1.
if ((bytes[20]! & 0x02) !== 0) return "animated";
return {
width: (bytes[24]! | (bytes[25]! << 8) | (bytes[26]! << 16)) + 1,
height: (bytes[27]! | (bytes[28]! << 8) | (bytes[29]! << 16)) + 1,
};
}
return null;
}
/** Decide from the bytes alone whether this is an avatar the server stores. */
export function checkAvatarImage(bytes: Uint8Array): AvatarImageCheck {
if (bytes.length === 0) return { ok: false, code: "AVATAR_IMAGE_EMPTY" };
if (bytes.length > AVATAR_IMAGE_MAX_BYTES) return { ok: false, code: "AVATAR_TOO_LARGE" };
let contentType: AvatarImageType;
let size: { width: number; height: number } | "animated" | null;
if (bytes.length >= 3 && bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) {
contentType = "image/jpeg";
size = jpegSize(bytes);
} else if (bytes.length >= 12 && ascii(bytes, 0, 4) === "RIFF" && ascii(bytes, 8, 4) === "WEBP") {
contentType = "image/webp";
size = webpSize(bytes);
} else {
// PNG, GIF, SVG, HEIC and everything else.
return { ok: false, code: "AVATAR_TYPE_UNSUPPORTED" };
}
if (size === "animated") return { ok: false, code: "AVATAR_TYPE_UNSUPPORTED" };
if (!size) return { ok: false, code: "AVATAR_IMAGE_INVALID" };
const { width, height } = size;
if (width !== height || width < AVATAR_IMAGE_MIN_SIDE || width > AVATAR_IMAGE_SIDE) {
return { ok: false, code: "AVATAR_DIMENSIONS_INVALID" };
}
return { ok: true, contentType, width, height };
}
/** The address the page shows the picture from; it changes whenever the picture does. */
export function avatarImageUrl(ref: AvatarImageRef): string {
return `${AVATAR_IMAGE_PATH}?v=${encodeURIComponent(ref.version)}`;
}
export function isAvatarImageVersion(value: unknown): value is string {
return typeof value === "string" && /^[0-9a-f]{16}$/.test(value);
}
/** Bytes as the database driver hands them back: a Buffer, or `\x…` text from a client that does not decode bytea. */
export function avatarImageBytes(value: unknown): Uint8Array | null {
if (value instanceof Uint8Array) return value;
if (typeof value === "string" && /^\\x([0-9a-f]{2})+$/i.test(value)) {
return Uint8Array.from(value.slice(2).match(/../g)!, (pair) => Number.parseInt(pair, 16));
}
return null;
}