AI-native design editor. Open-source Figma alternative.
feat: upload and crop Cloud account pictures, kept on the server (#1483)
Danila Poyarkov502a9d09e5bb
diff --git a/bun.lock b/bun.lockindex 1dde482bb..a60c58521 100644--- a/bun.lock+++ b/bun.lock@@ -225,7 +225,9 @@"fflate": "^0.8.3","hono": "^4.13.13","hono-rate-limiter": "^0.5.3",+ "image-size": "^2.0.4","jose": "^6.2.8",+ "js-base64": "^3.9.3","kysely": "^0.29.6","lib0": "^0.2.117","nodemailer": "^9.0.5",diff --git a/changes/1483/added.md b/changes/1483/added.mdnew file mode 100644index 000000000..911a225ae--- /dev/null+++ b/changes/1483/added.md@@ -0,0 +1 @@+- A Cloud server's Profile page uploads a picture, which you drag and zoom into the circle people see, and removes it again; administrators can take a person's picture down. The server keeps every picture itself, copying a linked Google account's picture at sign-in, so pages never load pictures from Google or Gravatar.diff --git a/changes/1483/changed.md b/changes/1483/changed.mdnew file mode 100644index 000000000..465cc1d7b--- /dev/null+++ b/changes/1483/changed.md@@ -0,0 +1 @@+- A Cloud server's Profile page changes your name in a dialog, as it already did your email, and confirms changes in a short notice at the top of the page; removing your picture asks first. **Account settings** in Home's account menu opens that page directly, and the menu shows your picture, name, email, and server.diff --git a/packages/cloud/AGENTS.md b/packages/cloud/AGENTS.mdindex bb8c5914f..195cfdf27 100644--- a/packages/cloud/AGENTS.md+++ b/packages/cloud/AGENTS.md@@ -14,6 +14,7 @@ Optional, self-hostable backend; the design is in `packages/docs/development/clo- Code inside Better Auth's own callbacks must not query the database, which deadlocks its transaction on one connection (`tests/integration/server/account/routes.test.ts`).- Name a table for what it holds, without a `cloud_` prefix; only a name Better Auth already uses gets a qualifier, such as `api_rate_limit` (`src/server/db/migrations/025_table_names.ts`).- Renaming a table that shipped migrations query gives them a type under the name they ran with, so their SQL stays the same (`LegacyAuthSchemaDatabase` in `src/server/db/migrations/helpers.ts`).+- `user.image` only ever holds an address this server serves; a picture from anywhere else is copied into `user_picture` or dropped, never linked (`src/server/pictures/service.ts`, `tests/integration/server/pictures/routes.test.ts`).- Database rows use `crypto.randomUUID()`; secrets that leave the server use `randomHex` from `@open-pencil/scene-graph/random`, are stored as SHA-256 digests (a single-use OAuth continuation keeps a JWE copy), and travel in URL fragments (`src/server/sharing/capabilities/service.ts`).- Every HTTP body goes through `validatedJSON` with a contract schema, and every response the client reads is parsed with Valibot (`src/server/validation.ts`, `src/client/api.ts`).- A revision's images live in `revision_image`; code that makes a revision from another copies them with `copyRevisionImages`, and a storage object a `workspace_image` holds is never unreferenced (`src/server/documents/images.ts`, `tests/integration/server/documents/images.test.ts`).diff --git a/packages/cloud/package.json b/packages/cloud/package.jsonindex c9a357ba8..968ca8855 100644--- a/packages/cloud/package.json+++ b/packages/cloud/package.json@@ -3,7 +3,11 @@"version": "0.15.1","private": true,"license": "Apache-2.0 AND MIT",+ "files": [+ "dist"+ ],"type": "module",+ "sideEffects": false,"imports": {"#cloud/*": {"types": "./src/*",@@ -46,10 +50,6 @@"default": "./dist/server.js"}},- "sideEffects": false,- "files": [- "dist"- ],"scripts": {"build": "bunx tsdown --config tsdown.config.ts","build:standalone": "bunx tsdown --config tsdown.standalone.config.ts",@@ -89,7 +89,9 @@"fflate": "^0.8.3","hono": "^4.13.13","hono-rate-limiter": "^0.5.3",+ "image-size": "^2.0.4","jose": "^6.2.8",+ "js-base64": "^3.9.3","kysely": "^0.29.6","lib0": "^0.2.117","nodemailer": "^9.0.5",@@ -100,9 +102,6 @@"ws": "^8.21.3","yjs": "^13.6.32"},- "optionalDependencies": {- "pg": "^8.23.0"- },"devDependencies": {"@cloudflare/workers-types": "^5.20261011.1","@electric-sql/pglite": "0.4.1",@@ -115,5 +114,8 @@"typescript": "~5.8.3","wrangler": "4.149.0","y-protocols": "^1.0.7"+ },+ "optionalDependencies": {+ "pg": "^8.23.0"}}diff --git a/packages/cloud/src/admin/api/routes.ts b/packages/cloud/src/admin/api/routes.tsindex e19ae97f5..2c45fe0ba 100644--- a/packages/cloud/src/admin/api/routes.ts+++ b/packages/cloud/src/admin/api/routes.ts@@ -17,7 +17,7 @@ import type { CloudAuthAdapter } from '#cloud/server/auth'import type { CloudDatabase } from '#cloud/server/db'import { CLOUD_RATE_LIMITS, createActorRateLimiter } from '#cloud/server/rate-limit'import { validatedJSON, validatedQuery } from '#cloud/server/validation'-import { Hono } from 'hono'+import { Hono, type Context } from 'hono'import { NoResultError, type Kysely } from 'kysely'import * as v from 'valibot'@@ -39,6 +39,19 @@ const parseLimitQuery = (input: unknown) => v.parse(v.object({ limit: countSchem/** Accounts are named by UUID; anything else names no one, rather than failing the query. */const accountIdSchema = v.pipe(v.string(), v.uuid())+/** Does what an administrator asked to another account; one that is not an account is not found. */+async function accountMutation(+ context: Context<CloudAPIEnvironment>,+ userId: string,+ mutate: (actorId: string, userId: string) => Promise<void>+) {+ if (!v.is(accountIdSchema, userId)) {+ return context.json({ error: { code: 'not_found' as const } }, 404)+ }+ await mutate(context.get('actor').userId, userId)+ return context.json({ ok: true as const })+}+export type CloudAdminServices = {email: AdminEmailServiceenrollment: EnrollmentService@@ -143,14 +156,16 @@ export function createCloudAdminRoutes(if (!detail) return context.json({ error: { code: 'not_found' as const } }, 404)return context.json(detail)})- .post('/users/reset-two-step', validatedJSON(parseUserMutation), async (context) => {- const { userId } = context.req.valid('json')- if (!v.is(accountIdSchema, userId)) {- return context.json({ error: { code: 'not_found' as const } }, 404)- }- await services.users.resetTwoStep(context.get('actor').userId, userId)- return context.json({ ok: true as const })- })+ .post('/users/reset-two-step', validatedJSON(parseUserMutation), (context) =>+ accountMutation(context, context.req.valid('json').userId, (actorId, userId) =>+ services.users.resetTwoStep(actorId, userId)+ )+ )+ .post('/users/remove-picture', validatedJSON(parseUserMutation), (context) =>+ accountMutation(context, context.req.valid('json').userId, (actorId, userId) =>+ services.users.removePicture(actorId, userId)+ )+ ).post('/users/ban', validatedJSON(parseUserMutation), async (context) => {const input = context.req.valid('json')await services.users.ban(diff --git a/packages/cloud/src/admin/users/service.ts b/packages/cloud/src/admin/users/service.tsindex f65b0d0d2..daa3fafbe 100644--- a/packages/cloud/src/admin/users/service.ts+++ b/packages/cloud/src/admin/users/service.ts@@ -7,6 +7,7 @@ import {type CloudAuthAdapter} from '#cloud/server/auth'import type { CloudDatabase } from '#cloud/server/db'+import type { UserPictureService } from '#cloud/server/pictures'import { dateString } from '#cloud/server/sharing/contracts'import { clamp, countBy, keyBy } from 'es-toolkit'import type { ExpressionBuilder, Kysely } from 'kysely'@@ -72,7 +73,12 @@ type UserRow = {export function createAdminUserService(database: Kysely<CloudDatabase>,auth: CloudAuthAdapter,- options: { requireMFA?: boolean; notify?: AuthenticationEmailService } = {}+ options: {+ requireMFA?: boolean+ notify?: AuthenticationEmailService+ /** Takes down a person's picture; without it, `removePicture` refuses. */+ pictures?: UserPictureService+ } = {}) {const activity = createSignInActivity(database)@@ -361,6 +367,18 @@ export function createAdminUserService(userId: user.id,change: 'reset-by-administrator'})+ },++ /** Takes down a person's picture, such as one that should not be shown; initials replace it. */+ async removePicture(actorId: string, userId: string): Promise<void> {+ if (!options.pictures) throw new Error('Pictures are not available')+ await database+ .selectFrom('user')+ .select('id')+ .where('id', '=', userId)+ .executeTakeFirstOrThrow()+ await options.pictures.remove(userId)+ await audit(actorId, 'user.picture-removed', userId)}}}diff --git a/packages/cloud/src/client/portal/account.ts b/packages/cloud/src/client/portal/account.tsindex 4452d374c..11fa590e5 100644--- a/packages/cloud/src/client/portal/account.ts+++ b/packages/cloud/src/client/portal/account.ts@@ -8,6 +8,7 @@ import {cloudMFAStatusResponseSchema,cloudMFAVerifyResponseSchema,cloudPasskeysResponseSchema,+ cloudPictureResponseSchema,cloudProfileResponseSchema,cloudSignInsResponseSchema,cloudSocialLinkResponseSchema@@ -120,6 +121,21 @@ export function createAccountAPI(call: CloudCall, { account }: PortalRouteClientsignal)},+ /** Shows `data`, a Base64 PNG or JPEG the page cropped and shrank, as the account's picture. */+ uploadPicture(data: string, signal?: AbortSignal) {+ return call(+ (options) => account.profile.picture.$put({ json: { data } }, options),+ cloudPictureResponseSchema,+ signal+ )+ },+ removePicture(signal?: AbortSignal) {+ return call(+ (options) => account.profile.picture.$delete(undefined, options),+ cloudAccountMutationResponseSchema,+ signal+ )+ },/** Sends a confirmation to the new address; the email changes once it is followed. */changeEmail(newEmail: string, callbackURL: string, signal?: AbortSignal) {return call(diff --git a/packages/cloud/src/client/portal/administration.ts b/packages/cloud/src/client/portal/administration.tsindex 4b4081295..8fcd0584b 100644--- a/packages/cloud/src/client/portal/administration.ts+++ b/packages/cloud/src/client/portal/administration.ts@@ -75,7 +75,7 @@ export function createAdministrationAPI(call: CloudCall, { admin, api }: PortalR)},userAction(- action: 'ban' | 'unban' | 'revoke-sessions' | 'reset-two-step',+ action: 'ban' | 'unban' | 'revoke-sessions' | 'reset-two-step' | 'remove-picture',userId: string,reason?: string,signal?: AbortSignaldiff --git a/packages/cloud/src/contract/account.ts b/packages/cloud/src/contract/account.tsindex 03ea55f86..014f39c8c 100644--- a/packages/cloud/src/contract/account.ts+++ b/packages/cloud/src/contract/account.ts@@ -1,3 +1,4 @@+import { isValid as isBase64 } from 'js-base64'import * as v from 'valibot'export const cloudAccountStateSchema = v.picklist(['active', 'pending', 'rejected', 'revoked'])@@ -45,7 +46,8 @@ export const accountSecurityErrorCodeSchema = v.picklist(['authentication_method_failed','email_unchanged','email_change_unavailable',- 'current_session'+ 'current_session',+ 'picture_invalid'])export const accountSecurityErrorResponseSchema = v.object({error: v.object({ code: accountSecurityErrorCodeSchema })@@ -98,12 +100,17 @@ export function parseCloudUnlinkAuthenticationMethod(input: unknown) {export const cloudAccountMutationResponseSchema = v.object({ ok: v.literal(true) })-/** What a person can see and change about themselves. */-export const cloudProfileSchema = v.object({+/** Who an account belongs to, as the portal shows it. */+export const cloudPersonSchema = v.object({id: v.string(),name: v.string(),email: v.pipe(v.string(), v.email()),- image: v.nullable(v.string()),+ /** The address of the account's picture, which the server serves; null shows initials. */+ image: v.nullable(v.string())+})+/** What a person can see and change about themselves. */+export const cloudProfileSchema = v.object({+ ...cloudPersonSchema.entries,createdAt: v.string(),/** Whether the server can send the verification a new email address needs. */emailChangeAvailable: v.boolean()@@ -112,6 +119,20 @@ export const cloudProfileResponseSchema = v.object({ profile: cloudProfileSchemaexport const cloudProfileUpdateSchema = v.object({name: v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(100))})+/** The largest picture an account may upload, once the page has cropped and shrunk it. */+export const CLOUD_PICTURE_MAX_BYTES = 256 * 1024+/** The width and height a page shrinks a picture to before it uploads it. */+export const CLOUD_PICTURE_SIZE = 256+export const cloudPictureUploadSchema = v.object({+ /** The picture's PNG or JPEG bytes, in Base64. */+ data: v.pipe(+ v.string(),+ v.maxLength(Math.ceil(CLOUD_PICTURE_MAX_BYTES / 3) * 4),+ v.check((value) => isBase64(value))+ )+})+/** The address the account's picture is now served from. */+export const cloudPictureResponseSchema = v.object({ image: v.string() })export const cloudEmailChangeSchema = v.object({newEmail: v.pipe(v.string(), v.trim(), v.toLowerCase(), v.email()),callbackURL: v.pipe(v.string(), v.url())@@ -159,6 +180,9 @@ export const cloudSignInsResponseSchema = v.object({ signIns: v.array(cloudSignIexport function parseCloudProfileUpdate(input: unknown) {return v.parse(cloudProfileUpdateSchema, input)}+export function parseCloudPictureUpload(input: unknown) {+ return v.parse(cloudPictureUploadSchema, input)+}export function parseCloudEmailChange(input: unknown) {return v.parse(cloudEmailChangeSchema, input)}diff --git a/packages/cloud/src/contract/admin/index.ts b/packages/cloud/src/contract/admin/index.tsindex 7ef2a39b7..848e19230 100644--- a/packages/cloud/src/contract/admin/index.ts+++ b/packages/cloud/src/contract/admin/index.ts@@ -1,6 +1,11 @@import * as v from 'valibot'-import { cloudIdentitySchema, cloudAccountSessionSchema, cloudSignInSchema } from '../account'+import {+ cloudIdentitySchema,+ cloudAccountSessionSchema,+ cloudPersonSchema,+ cloudSignInSchema+} from '../account'import { workspaceRoleSchema } from '../workspaces'const timestampSchema = v.pipe(v.string(), v.isoTimestamp())@@ -46,10 +51,7 @@ export const cloudAdminSessionResponseSchema = v.object({ user: cloudIdentitySchconst countSchema = v.pipe(v.number(), v.integer(), v.minValue(0))export const cloudAdminUserSchema = v.object({- id: v.string(),- name: v.string(),- email: v.pipe(v.string(), v.email()),- image: v.nullable(v.string()),+ ...cloudPersonSchema.entries,role: v.optional(v.string()),banned: v.nullable(v.boolean()),banReason: v.optional(v.nullable(v.string())),diff --git a/packages/cloud/src/server/account/routes.ts b/packages/cloud/src/server/account/routes.tsindex 20ae5df2c..4fb795ff8 100644--- a/packages/cloud/src/server/account/routes.ts+++ b/packages/cloud/src/server/account/routes.ts@@ -8,6 +8,8 @@ import {parseCloudUnlinkAuthenticationMethod,parseCloudEmailChange,parseCloudProfileUpdate,+ parseCloudPictureUpload,+ CLOUD_PICTURE_MAX_BYTES,parseCloudSessionRevoke} from '#cloud/contract'import type { CloudAPIEnvironment } from '#cloud/server/api'@@ -18,15 +20,22 @@ import {type CloudSessionResolver} from '#cloud/server/auth'import type { CloudServerConfig } from '#cloud/server/config'+import { PictureInvalidError, type UserPictureService } from '#cloud/server/pictures'import { validatedJSON } from '#cloud/server/validation'import type { WorkspaceService } from '#cloud/server/workspaces'import { Hono, type MiddlewareHandler } from 'hono'+import { bodyLimit } from 'hono/body-limit'+import { toUint8Array } from 'js-base64'import { createAccountActions } from './actions'+/** Room for a Base64 picture and the JSON around it. */+const PICTURE_BODY_BYTES = Math.ceil(CLOUD_PICTURE_MAX_BYTES / 3) * 4 + 1024+export type AccountRouteDependencies = {auth: CloudAuthAdapterconfig: CloudServerConfig+ pictures: UserPictureServiceenrollment: EnrollmentServiceworkspaces: WorkspaceServiceresolveIdentity: CloudIdentityResolver@@ -217,6 +226,28 @@ export function createAccountRoutes(services: AccountRouteDependencies) {)return result instanceof Response ? result : context.json({ ok: true as const })})+ .put(+ '/api/account/profile/picture',+ bodyLimit({+ maxSize: PICTURE_BODY_BYTES,+ onError: (context) => context.json({ error: { code: 'picture_invalid' as const } }, 413)+ }),+ validatedJSON(parseCloudPictureUpload),+ async (context) => {+ const bytes = toUint8Array(context.req.valid('json').data)+ try {+ const image = await services.pictures.upload(context.get('actor').userId, bytes)+ return context.json({ image })+ } catch (error) {+ if (!(error instanceof PictureInvalidError)) throw error+ return context.json({ error: { code: 'picture_invalid' as const } }, 400)+ }+ }+ )+ .delete('/api/account/profile/picture', async (context) => {+ await services.pictures.remove(context.get('actor').userId)+ return context.json({ ok: true as const })+ }).post('/api/account/profile/email', validatedJSON(parseCloudEmailChange), async (context) => {const result = await accountAction(() => accountAuthentication.changeEmail(context.req.raw.headers, context.req.valid('json')),diff --git a/packages/cloud/src/server/app.ts b/packages/cloud/src/server/app.tsindex eb3b7e344..1cad2d2a6 100644--- a/packages/cloud/src/server/app.ts+++ b/packages/cloud/src/server/app.ts@@ -41,6 +41,7 @@ import type { TransactionalEmailService } from '#cloud/server/email'import { createInternalRoutes, createInternalService } from '#cloud/server/internal'import type { InvitationDelivery, InvitationOutbox } from '#cloud/server/invitations'import type { ObjectStore } from '#cloud/server/objects'+import { createPictureRoutes, createUserPictures } from '#cloud/server/pictures'import {createConfiguredCloudPolicy,createDefaultCloudPolicy,@@ -169,6 +170,7 @@ export function createCloudApp(services: CloudServices) {maxAge: 600})const workspaces = createWorkspaceService(services.database)+ const pictures = createUserPictures(services.database, { publicURL: services.config.publicURL })const workspaceMembers = createWorkspaceMemberService(services.database, {email: services.transactionalEmail,publicURL: services.config.publicURL@@ -188,6 +190,7 @@ export function createCloudApp(services: CloudServices) {enrollment,users: createAdminUserService(services.database, services.auth, {requireMFA: services.config.deploymentAdminMFARequired,+ pictures,notify: services.transactionalEmail? createAuthenticationEmailService(services.transactionalEmail, services.config.publicURL): undefined@@ -297,6 +300,7 @@ export function createCloudApp(services: CloudServices) {const accountRoutes = createAccountRoutes({auth: services.auth,+ pictures,config: services.config,enrollment,workspaces,@@ -398,6 +402,7 @@ export function createCloudApp(services: CloudServices) {return services.auth.handler(context.req.raw)}).route('/', accountRoutes)+ .route('/', createPictureRoutes(pictures)).use('/api/shares/:shareId/collaboration-ticket', publicCollaborationLimiter).use('/api/public/*', publicRateLimiter).use('/api/shares/*', publicRateLimiter)diff --git a/packages/cloud/src/server/auth/factory.ts b/packages/cloud/src/server/auth/factory.tsindex a42772bdb..c516ce023 100644--- a/packages/cloud/src/server/auth/factory.ts+++ b/packages/cloud/src/server/auth/factory.ts@@ -1,6 +1,7 @@import { createEnrollmentService, type EnrollmentService } from '#cloud/admin/enrollment/service'import type { CloudServerConfig } from '#cloud/server/config'import type { CloudDatabase } from '#cloud/server/db'+import { createUserPictures, providerPictures } from '#cloud/server/pictures'import { passkey } from '@better-auth/passkey'import { APIError, betterAuth, type BetterAuthOptions } from 'better-auth'import { getMigrations } from 'better-auth/db/migration'@@ -304,7 +305,8 @@ export function createBetterAuthAdapter(validateClient: (clientId) => clientId.startsWith('openpencil-desktop:')}),// After two-step sign-in's own hooks, so a sign-in waiting for its second step is skipped.- accountActivity(activity, (user) => notifyTwoStep(user, 'passkey-added'))+ accountActivity(activity, (user) => notifyTwoStep(user, 'passkey-added')),+ providerPictures(createUserPictures(database, { publicURL: config.publicURL }))],socialProviders: socialProviders(config),trustedOrigins: [diff --git a/packages/cloud/src/server/db/index.ts b/packages/cloud/src/server/db/index.tsindex 5b747c20c..86f023ad1 100644--- a/packages/cloud/src/server/db/index.ts+++ b/packages/cloud/src/server/db/index.ts@@ -15,6 +15,7 @@ export type {TransactionalEmailStatus,Upload,UploadStatus,+ UserPictureFormat,Workspace,WorkspaceUpdate} from './tables'diff --git a/packages/cloud/src/server/db/migrate.ts b/packages/cloud/src/server/db/migrate.tsindex c02766f24..01ddea892 100644--- a/packages/cloud/src/server/db/migrate.ts+++ b/packages/cloud/src/server/db/migrate.ts@@ -26,6 +26,7 @@ import * as entitlementExternalVersion from './migrations/022_entitlement_externimport * as documentImages from './migrations/023_document_images'import * as accountActivity from './migrations/024_account_activity'import * as tableNames from './migrations/025_table_names'+import * as userPicture from './migrations/026_user_picture'import type { CloudDatabase } from './tables'const migrations: Record<string, Migration> = {@@ -53,7 +54,8 @@ const migrations: Record<string, Migration> = {'022_entitlement_external_version': entitlementExternalVersion,'023_document_images': documentImages,'024_account_activity': accountActivity,- '025_table_names': tableNames+ '025_table_names': tableNames,+ '026_user_picture': userPicture}class CloudMigrationProvider implements MigrationProvider {diff --git a/packages/cloud/src/server/db/migrations/026_user_picture.ts b/packages/cloud/src/server/db/migrations/026_user_picture.tsnew file mode 100644index 000000000..300acd0d4--- /dev/null+++ b/packages/cloud/src/server/db/migrations/026_user_picture.ts@@ -0,0 +1,30 @@+import { checkColumnIn, CURRENT_TIMESTAMP } from '#cloud/server/db/expressions'+import type { Kysely } from 'kysely'++/**+ * The picture each account shows, kept by the server so pages never load one from another+ * service: one uploaded by its owner, or the one a linked Google account gave it, copied at sign-in.+ */+export async function up(database: Kysely<unknown>): Promise<void> {+ await database.schema+ .createTable('user_picture')+ // Better Auth's tables may come after this migration, so the account is not a foreign key.+ .addColumn('user_id', 'uuid', (column) => column.primaryKey())+ .addColumn('bytes', 'bytea', (column) => column.notNull())+ .addColumn('format', 'text', (column) => column.notNull())+ .addColumn('checksum', 'text', (column) => column.notNull())+ .addColumn('source', 'text', (column) => column.notNull())+ .addColumn('created_at', 'timestamptz', (column) =>+ column.notNull().defaultTo(CURRENT_TIMESTAMP)+ )+ .addCheckConstraint('user_picture_format_check', checkColumnIn('format', ['png', 'jpeg']))+ .addCheckConstraint(+ 'user_picture_source_check',+ checkColumnIn('source', ['upload', 'provider'])+ )+ .execute()+}++export async function down(database: Kysely<unknown>): Promise<void> {+ await database.schema.dropTable('user_picture').execute()+}diff --git a/packages/cloud/src/server/db/tables.ts b/packages/cloud/src/server/db/tables.tsindex b81aacfd7..74f650858 100644--- a/packages/cloud/src/server/db/tables.ts+++ b/packages/cloud/src/server/db/tables.ts@@ -218,6 +218,19 @@ export interface SignInTable {createdAt: TimestampColumn}+export type UserPictureFormat = 'png' | 'jpeg'++/** The picture an account shows: uploaded by its owner, or copied from a linked account. */+export interface UserPictureTable {+ userId: string+ bytes: Uint8Array+ format: UserPictureFormat+ /** The SHA-256 of the bytes, hex, which names this picture in its address. */+ checksum: string+ source: 'upload' | 'provider'+ createdAt: TimestampColumn+}+export interface DocumentCollaborationStateTable {documentId: stringroomEpoch: number@@ -330,6 +343,7 @@ export interface CloudDatabase {passkey: PasskeyTablemfaAssurance: MFAAssuranceTablesignIn: SignInTable+ userPicture: UserPictureTableuser: AuthUserTableauthSchemaVersion: AuthSchemaVersionTableenrollment: EnrollmentTablediff --git a/packages/cloud/src/server/pictures/index.ts b/packages/cloud/src/server/pictures/index.tsnew file mode 100644index 000000000..e82433eaa--- /dev/null+++ b/packages/cloud/src/server/pictures/index.ts@@ -0,0 +1,9 @@+export { providerPictures } from './provider'+export { createPictureRoutes } from './routes'+export {+ createUserPictures,+ PICTURE_PATH,+ PictureInvalidError,+ pictureFormat,+ type UserPictureService+} from './service'diff --git a/packages/cloud/src/server/pictures/provider.ts b/packages/cloud/src/server/pictures/provider.tsnew file mode 100644index 000000000..02f98acdf--- /dev/null+++ b/packages/cloud/src/server/pictures/provider.ts@@ -0,0 +1,56 @@+import { signInMethod } from '#cloud/server/auth/activity'+import type { BetterAuthPlugin } from 'better-auth'+import { createAuthMiddleware } from 'better-auth/api'++import type { UserPictureService } from './service'++/** Whether an endpoint signs in with another service, which may name the person's picture. */+function providerSignIn(context: { path?: string } | null): boolean {+ const path = context?.path ?? ''+ return path.startsWith('/callback/') || path === '/sign-in/social'+}++/**+ * Keeps the picture a Google account gave the person once a sign-in issues their session, so pages+ * show the server's copy and never load it from Google. Accounts made before the server kept+ * pictures move over the next time they sign in this way. Better Auth also takes an `image` on+ * email sign-up and user updates; only a provider's sign-in may set one through it, since the+ * server fetches it, and the server writes its own addresses itself.+ */+export function providerPictures(pictures: UserPictureService): BetterAuthPlugin {+ const refused = (image: unknown, context: { path?: string } | null) =>+ image !== undefined && image !== null && !providerSignIn(context)+ return {+ id: 'openpencil-provider-pictures',+ init: () => ({+ options: {+ databaseHooks: {+ user: {+ create: {+ before: async (user, context) =>+ refused(user.image, context) ? { data: { ...user, image: null } } : true+ },+ update: {+ // Better Auth merges what a hook returns into the update, so `image` is unset.+ before: async (user, context) =>+ refused(user.image, context) ? { data: { image: undefined } } : true+ }+ }+ }+ }+ }),+ hooks: {+ after: [+ {+ matcher: (context) => signInMethod(context) !== null,+ handler: createAuthMiddleware(async (context) => {+ const user = context.context.newSession?.user+ if (user?.image && !pictures.served(user.image)) {+ await pictures.copyFromProvider(user.id, user.image)+ }+ })+ }+ ]+ }+ }+}diff --git a/packages/cloud/src/server/pictures/routes.ts b/packages/cloud/src/server/pictures/routes.tsnew file mode 100644index 000000000..49362b5fb--- /dev/null+++ b/packages/cloud/src/server/pictures/routes.ts@@ -0,0 +1,21 @@+import { Hono } from 'hono'++import { PICTURE_PATH, type UserPictureService } from './service'++/**+ * Account pictures, for anyone with a picture's address: pages show people to those they share+ * documents and workspaces with, and the desktop app shows them from another origin.+ */+export function createPictureRoutes(pictures: UserPictureService) {+ return new Hono().get(`${PICTURE_PATH}/:userId/:version`, async (context) => {+ const picture = await pictures.read(context.req.param('userId'), context.req.param('version'))+ if (!picture) return context.json({ error: { code: 'not_found' as const } }, 404)+ // The address changes with the picture, but a removed one must stop showing within a day.+ context.header('Cache-Control', 'public, max-age=86400')+ context.header('Content-Type', `image/${picture.format}`)+ context.header('X-Content-Type-Options', 'nosniff')+ context.header('Content-Security-Policy', "default-src 'none'; sandbox")+ context.header('Cross-Origin-Resource-Policy', 'cross-origin')+ return context.body(new Uint8Array(picture.bytes))+ })+}diff --git a/packages/cloud/src/server/pictures/service.ts b/packages/cloud/src/server/pictures/service.tsnew file mode 100644index 000000000..861c61457--- /dev/null+++ b/packages/cloud/src/server/pictures/service.ts@@ -0,0 +1,191 @@+import { CLOUD_PICTURE_MAX_BYTES } from '#cloud/contract'+import type { CloudDatabase, UserPictureFormat } from '#cloud/server/db'+import { sha256 } from '@noble/hashes/sha2.js'+import { bytesToHex } from '@noble/hashes/utils.js'+import { imageSize } from 'image-size'+import type { Kysely } from 'kysely'+import * as v from 'valibot'++/** Where pictures are served; a picture's address ends in its checksum, so a new one is new. */+export const PICTURE_PATH = '/api/pictures'+/** The longest side a stored picture may have; pages send 256 pixels. */+const PICTURE_MAX_SIDE = 1024+/** How many hex digits of the checksum name a picture in its address. */+const PICTURE_VERSION_LENGTH = 16+/** How long a linked account's picture may take to fetch before sign-in goes on without it. */+const PROVIDER_PICTURE_TIMEOUT_MS = 5000+/** The hosts linked accounts serve pictures from; Google is the only provider that sends one. */+const PROVIDER_PICTURE_HOSTS = ['googleusercontent.com']+const PICTURE_FORMATS: Readonly<Record<string, UserPictureFormat>> = { png: 'png', jpg: 'jpeg' }+const userIdSchema = v.pipe(v.string(), v.uuid())++/** The bytes are not a PNG or JPEG picture the server keeps. */+export class PictureInvalidError extends Error {+ constructor() {+ super('The picture must be a PNG or JPEG image of at most 1024 by 1024 pixels')+ this.name = 'PictureInvalidError'+ }+}++/** The format of a picture the server keeps, read from its bytes; anything else is null. */+export function pictureFormat(bytes: Uint8Array): UserPictureFormat | null {+ if (bytes.byteLength === 0 || bytes.byteLength > CLOUD_PICTURE_MAX_BYTES) return null+ try {+ const size = imageSize(bytes)+ const format = size.type ? PICTURE_FORMATS[size.type] : undefined+ if (!format || size.width < 1 || size.height < 1) return null+ if (size.width > PICTURE_MAX_SIDE || size.height > PICTURE_MAX_SIDE) return null+ return format+ } catch {+ return null+ }+}++/** Whether `url` is an HTTPS address on a host a linked account's picture comes from. */+function providerPicture(url: URL): boolean {+ return (+ url.protocol === 'https:' &&+ PROVIDER_PICTURE_HOSTS.some(+ (host) => url.hostname === host || url.hostname.endsWith(`.${host}`)+ )+ )+}++/** Reads at most `limit` bytes of a response body, or null when it holds more. */+async function boundedBody(response: Response, limit: number): Promise<Uint8Array | null> {+ if (!response.body) return null+ const reader = response.body.getReader()+ const chunks: Uint8Array[] = []+ let length = 0+ for (;;) {+ const { done, value } = await reader.read()+ if (done) break+ length += value.byteLength+ if (length > limit) {+ await reader.cancel()+ return null+ }+ chunks.push(value)+ }+ const bytes = new Uint8Array(length)+ let offset = 0+ for (const chunk of chunks) {+ bytes.set(chunk, offset)+ offset += chunk.byteLength+ }+ return bytes+}++export type UserPictureOptions = {+ publicURL: string+ /** Fetches a linked account's picture; tests pass their own. */+ fetch?: (url: string, init: RequestInit) => Promise<Response>+}++/**+ * The picture each account shows. The server keeps the bytes and serves them itself, so a page+ * that shows a person never asks another service for them; `user.image` holds their address.+ */+export function createUserPictures(database: Kysely<CloudDatabase>, options: UserPictureOptions) {+ const fetchPicture = options.fetch ?? ((url, init) => fetch(url, init))+ const origin = new URL(options.publicURL).origin++ function address(userId: string, checksum: string): string {+ return `${origin}${PICTURE_PATH}/${userId}/${checksum.slice(0, PICTURE_VERSION_LENGTH)}`+ }++ /** Whether `image` is a picture this server serves, rather than another service's. */+ function served(image: string): boolean {+ return image.startsWith(`${origin}${PICTURE_PATH}/`)+ }++ async function save(+ userId: string,+ bytes: Uint8Array,+ source: 'upload' | 'provider'+ ): Promise<string> {+ const format = pictureFormat(bytes)+ if (!format) throw new PictureInvalidError()+ const checksum = bytesToHex(sha256(bytes))+ const image = address(userId, checksum)+ const createdAt = new Date()+ await database.transaction().execute(async (transaction) => {+ await transaction+ .insertInto('userPicture')+ .values({ userId, bytes, format, checksum, source, createdAt })+ .onConflict((conflict) =>+ conflict.column('userId').doUpdateSet({ bytes, format, checksum, source, createdAt })+ )+ .execute()+ await transaction+ .updateTable('user')+ .set({ image, updatedAt: createdAt })+ .where('id', '=', userId)+ .execute()+ })+ return image+ }++ async function remove(userId: string): Promise<void> {+ await database.transaction().execute(async (transaction) => {+ await transaction.deleteFrom('userPicture').where('userId', '=', userId).execute()+ await transaction+ .updateTable('user')+ .set({ image: null, updatedAt: new Date() })+ .where('id', '=', userId)+ .execute()+ })+ }++ return {+ served,++ /** Keeps a picture the account's owner uploaded and shows it from now on. */+ upload(userId: string, bytes: Uint8Array): Promise<string> {+ return save(userId, bytes, 'upload')+ },++ /** Goes back to initials. */+ remove,++ /** The picture at `/api/pictures/:userId/:version`, or null for any other address. */+ async read(userId: string, version: string) {+ if (!v.is(userIdSchema, userId) || version.length !== PICTURE_VERSION_LENGTH) return null+ const picture = await database+ .selectFrom('userPicture')+ .select(['bytes', 'format', 'checksum'])+ .where('userId', '=', userId)+ .executeTakeFirst()+ return picture?.checksum.startsWith(version) ? picture : null+ },++ /**+ * Keeps the picture a linked account named in `image` and shows it instead, so pages never+ * load it from that service. A picture that cannot be fetched or is not one the server keeps+ * leaves initials in its place. An uploaded picture stays.+ */+ async copyFromProvider(userId: string, image: string): Promise<void> {+ if (served(image)) return+ try {+ if (!providerPicture(new URL(image))) throw new PictureInvalidError()+ const response = await fetchPicture(image, {+ redirect: 'error',+ signal: AbortSignal.timeout(PROVIDER_PICTURE_TIMEOUT_MS)+ })+ const bytes = response.ok ? await boundedBody(response, CLOUD_PICTURE_MAX_BYTES) : null+ if (!bytes) throw new PictureInvalidError()+ await save(userId, bytes, 'provider')+ } catch (error) {+ console.warn('Keeping a linked account picture failed', error)+ await database+ .updateTable('user')+ .set({ image: null, updatedAt: new Date() })+ .where('id', '=', userId)+ .where('image', '=', image)+ .execute()+ }+ }+ }+}++export type UserPictureService = ReturnType<typeof createUserPictures>diff --git a/packages/cloud/tests/helpers/account-authentication.ts b/packages/cloud/tests/helpers/account-authentication.tsindex 435df277a..036fe95a5 100644--- a/packages/cloud/tests/helpers/account-authentication.ts+++ b/packages/cloud/tests/helpers/account-authentication.ts@@ -40,13 +40,13 @@ export function accountAuthenticationRequest(path: string,body?: object,cookie?: string,- init: { headers?: Record<string, string> } = {}+ init: { headers?: Record<string, string>; method?: string } = {}): Request {const headers = new Headers(init.headers)if (body) headers.set('Content-Type', 'application/json')if (cookie) headers.set('Cookie', cookie)return new Request(new URL(path, accountAuthenticationConfig.publicURL), {- method: body ? 'POST' : 'GET',+ method: init.method ?? (body ? 'POST' : 'GET'),headers,body: body ? JSON.stringify(body) : undefined})@@ -133,13 +133,14 @@ export async function approveAccount(export async function createVerifiedCredentialAccount(fixture: Awaited<ReturnType<typeof createAccountAuthenticationFixture>>,- input: { email: string; name: string; password: string; approved: boolean }+ input: { email: string; name: string; password: string; approved: boolean; image?: string }): Promise<{ userId: string; sessionCookie: string }> {await fixture.app.fetch(accountAuthenticationRequest('/api/auth/sign-up/email', {name: input.name,email: input.email,- password: input.password+ password: input.password,+ image: input.image}))const user = await fixture.databasediff --git a/packages/cloud/tests/helpers/pictures.ts b/packages/cloud/tests/helpers/pictures.tsnew file mode 100644index 000000000..e613bdf2f--- /dev/null+++ b/packages/cloud/tests/helpers/pictures.ts@@ -0,0 +1,13 @@+/**+ * The start of a PNG of the given size, its signature and header chunk: all the server reads to+ * learn a picture's type and size.+ */+export function pngHeader(width: number, height: number): Uint8Array<ArrayBuffer> {+ const bytes = new Uint8Array(33)+ bytes.set([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 13, 0x49, 0x48, 0x44, 0x52])+ const view = new DataView(bytes.buffer)+ view.setUint32(16, width)+ view.setUint32(20, height)+ bytes.set([8, 6, 0, 0, 0], 24)+ return bytes+}diff --git a/packages/cloud/tests/integration/admin/users/service.test.ts b/packages/cloud/tests/integration/admin/users/service.test.tsindex 8f0357a4c..b768863e8 100644--- a/packages/cloud/tests/integration/admin/users/service.test.ts+++ b/packages/cloud/tests/integration/admin/users/service.test.ts@@ -2,7 +2,9 @@ import { describe, expect, test } from 'bun:test'import { ignoredSecurityNotices } from '#cloud-tests/helpers/account-authentication'import { createCloudTestDatabase } from '#cloud-tests/helpers/database'+import { pngHeader } from '#cloud-tests/helpers/pictures'import { createAdminAuditService, createAdminUserService } from '#cloud/server'+import { createUserPictures } from '#cloud/server/pictures'const ADMIN_ID = '11111111-1111-4111-8111-111111111111'const USER_ID = '22222222-2222-4222-8222-222222222222'@@ -335,4 +337,59 @@ describe('deployment admin user safety', () => {await runtime.close()}})++ test('takes down a person’s picture and records it', async () => {+ const runtime = await createCloudTestDatabase()+ try {+ await runtime.database+ .insertInto('user')+ .values([+ {+ id: ADMIN_ID,+ name: 'Admin',+ email: '[email protected]',+ emailVerified: true,+ image: null,+ role: 'admin',+ banned: false+ },+ {+ id: USER_ID,+ name: 'Pictured',+ email: '[email protected]',+ emailVerified: true,+ image: null,+ role: 'user',+ banned: false+ }+ ])+ .execute()+ const pictures = createUserPictures(runtime.database, {+ publicURL: 'https://cloud.example.com'+ })+ await pictures.upload(USER_ID, pngHeader(256, 256))+ await expect(+ createAdminUserService(runtime.database, authAdapter()).removePicture(ADMIN_ID, USER_ID)+ ).rejects.toThrow('not available')++ const service = createAdminUserService(runtime.database, authAdapter(), { pictures })+ await service.removePicture(ADMIN_ID, USER_ID)+ const user = await runtime.database+ .selectFrom('user')+ .select('image')+ .where('id', '=', USER_ID)+ .executeTakeFirstOrThrow()+ expect(user.image).toBeNull()+ const kept = await runtime.database.selectFrom('userPicture').select('userId').execute()+ expect(kept).toEqual([])+ expect(await createAdminAuditService(runtime.database).list()).toEqual([+ expect.objectContaining({+ action: 'user.picture-removed',+ subject: { type: 'user', id: USER_ID, name: 'Pictured' }+ })+ ])+ } finally {+ await runtime.close()+ }+ })})diff --git a/packages/cloud/tests/integration/server/pictures/routes.test.ts b/packages/cloud/tests/integration/server/pictures/routes.test.tsnew file mode 100644index 000000000..40b1cf134--- /dev/null+++ b/packages/cloud/tests/integration/server/pictures/routes.test.ts@@ -0,0 +1,213 @@+import { describe, expect, test } from 'bun:test'++import {+ accountAuthenticationConfig,+ accountAuthenticationRequest,+ createAccountAuthenticationFixture,+ createVerifiedCredentialAccount+} from '#cloud-tests/helpers/account-authentication'+import { pngHeader } from '#cloud-tests/helpers/pictures'+import { responseJSON } from '#cloud-tests/helpers/response'+import {+ accountSecurityErrorResponseSchema,+ cloudPictureResponseSchema,+ cloudProfileResponseSchema+} from '#cloud/contract'+import { createUserPictures } from '#cloud/server/pictures'+import { utf8ToBytes } from '@noble/hashes/utils.js'+import { fromUint8Array } from 'js-base64'++const PASSWORD = 'a sufficiently long password'+const GOOGLE_PICTURE = 'https://lh3.googleusercontent.com/a/picture=s96-c'++type Fixture = Awaited<ReturnType<typeof createAccountAuthenticationFixture>>++async function profileImage(fixture: Fixture, cookie: string): Promise<string | null> {+ const response = await fixture.app.fetch(+ accountAuthenticationRequest('/api/account/profile', undefined, cookie)+ )+ return (await responseJSON(response, cloudProfileResponseSchema)).profile.image+}++function upload(fixture: Fixture, bytes: Uint8Array, cookie?: string) {+ return fixture.app.fetch(+ accountAuthenticationRequest(+ '/api/account/profile/picture',+ { data: fromUint8Array(bytes) },+ cookie,+ { method: 'PUT' }+ )+ )+}++describe('account pictures', () => {+ test('serves an uploaded picture from its own address until it is removed', async () => {+ const fixture = await createAccountAuthenticationFixture()+ try {+ const account = await createVerifiedCredentialAccount(fixture, {+ email: '[email protected]',+ name: 'Picture Person',+ password: PASSWORD,+ approved: true+ })+ const picture = pngHeader(256, 256)+ const uploaded = await upload(fixture, picture, account.sessionCookie)+ expect(uploaded.status).toBe(200)+ const { image } = await responseJSON(uploaded, cloudPictureResponseSchema)+ expect(image).toStartWith(+ `${accountAuthenticationConfig.publicURL}/api/pictures/${account.userId}/`+ )+ expect(await profileImage(fixture, account.sessionCookie)).toBe(image)++ const served = await fixture.app.fetch(new Request(image))+ expect(served.status).toBe(200)+ expect(served.headers.get('content-type')).toBe('image/png')+ expect(served.headers.get('cache-control')).toBe('public, max-age=86400')+ expect(served.headers.get('x-content-type-options')).toBe('nosniff')+ expect(new Uint8Array(await served.arrayBuffer())).toEqual(picture)++ const elsewhere = [+ `/api/pictures/${account.userId}/0000000000000000`,+ `/api/pictures/not-an-account/${image.slice(-16)}`+ ]+ for (const path of elsewhere) {+ const missing = await fixture.app.fetch(accountAuthenticationRequest(path))+ expect(missing.status).toBe(404)+ }++ const removed = await fixture.app.fetch(+ accountAuthenticationRequest(+ '/api/account/profile/picture',+ undefined,+ account.sessionCookie,+ {+ method: 'DELETE'+ }+ )+ )+ expect(removed.status).toBe(200)+ expect(await profileImage(fixture, account.sessionCookie)).toBeNull()+ expect((await fixture.app.fetch(new Request(image))).status).toBe(404)+ } finally {+ await fixture.close()+ }+ })++ test('refuses files that are not a picture the server keeps', async () => {+ const fixture = await createAccountAuthenticationFixture()+ try {+ const account = await createVerifiedCredentialAccount(fixture, {+ email: '[email protected]',+ name: 'Refused Person',+ password: PASSWORD,+ approved: true+ })+ for (const bytes of [utf8ToBytes('<svg/>'), pngHeader(4096, 4096)]) {+ const refused = await upload(fixture, bytes, account.sessionCookie)+ expect(refused.status).toBe(400)+ expect((await responseJSON(refused, accountSecurityErrorResponseSchema)).error.code).toBe(+ 'picture_invalid'+ )+ }+ expect(await profileImage(fixture, account.sessionCookie)).toBeNull()+ expect((await upload(fixture, pngHeader(256, 256))).status).toBe(401)+ } finally {+ await fixture.close()+ }+ })++ test("keeps a linked account's picture instead of linking to it", async () => {+ const fixture = await createAccountAuthenticationFixture()+ try {+ const account = await createVerifiedCredentialAccount(fixture, {+ email: '[email protected]',+ name: 'Google Person',+ password: PASSWORD,+ approved: true+ })+ const picture = pngHeader(96, 96)+ const requested: string[] = []+ const pictures = createUserPictures(fixture.database, {+ publicURL: accountAuthenticationConfig.publicURL,+ fetch: async (input) => {+ requested.push(String(input))+ return new Response(picture)+ }+ })+ const setImage = (image: string) =>+ fixture.database+ .updateTable('user')+ .set({ image })+ .where('id', '=', account.userId)+ .execute()++ await setImage(GOOGLE_PICTURE)+ await pictures.copyFromProvider(account.userId, GOOGLE_PICTURE)+ expect(requested).toEqual([GOOGLE_PICTURE])+ const kept = await profileImage(fixture, account.sessionCookie)+ expect(kept).toStartWith(`${accountAuthenticationConfig.publicURL}/api/pictures/`)+ const served = await fixture.app.fetch(new Request(kept ?? ''))+ expect(new Uint8Array(await served.arrayBuffer())).toEqual(picture)++ // A kept picture is not fetched again.+ await pictures.copyFromProvider(account.userId, kept ?? '')+ expect(requested).toHaveLength(1)++ // One that cannot be kept leaves initials rather than a link to another service.+ const failing = createUserPictures(fixture.database, {+ publicURL: accountAuthenticationConfig.publicURL,+ fetch: async () => new Response('not found', { status: 404 })+ })+ await setImage(GOOGLE_PICTURE)+ await failing.copyFromProvider(account.userId, GOOGLE_PICTURE)+ expect(await profileImage(fixture, account.sessionCookie)).toBeNull()+ for (const elsewhere of [+ 'http://lh3.googleusercontent.com/plain.png',+ 'https://pictures.example.com/picture.png',+ 'https://googleusercontent.com.example.com/picture.png'+ ]) {+ await setImage(elsewhere)+ await pictures.copyFromProvider(account.userId, elsewhere)+ expect(await profileImage(fixture, account.sessionCookie)).toBeNull()+ }+ expect(requested).toHaveLength(1)+ } finally {+ await fixture.close()+ }+ })++ test('takes a picture address only from a linked account', async () => {+ const fixture = await createAccountAuthenticationFixture()+ try {+ const account = await createVerifiedCredentialAccount(fixture, {+ email: '[email protected]',+ name: 'Address Person',+ password: PASSWORD,+ approved: true,+ image: GOOGLE_PICTURE+ })+ expect(await profileImage(fixture, account.sessionCookie)).toBeNull()++ // Nor may it name an address that looks like one the server serves.+ const lookalike = `${accountAuthenticationConfig.publicURL}/api/pictures/${account.userId}/0000000000000000`+ for (const image of [GOOGLE_PICTURE, lookalike]) {+ const updated = await fixture.app.fetch(+ accountAuthenticationRequest(+ '/api/auth/update-user',+ { name: 'Renamed Person', image },+ account.sessionCookie+ )+ )+ expect(updated.status).toBe(200)+ expect(await profileImage(fixture, account.sessionCookie)).toBeNull()+ }+ const profile = await fixture.app.fetch(+ accountAuthenticationRequest('/api/account/profile', undefined, account.sessionCookie)+ )+ const { name, image } = (await responseJSON(profile, cloudProfileResponseSchema)).profile+ expect({ name, image }).toEqual({ name: 'Renamed Person', image: null })+ } finally {+ await fixture.close()+ }+ })+})diff --git a/packages/cloud/tests/server/pictures/service.test.ts b/packages/cloud/tests/server/pictures/service.test.tsnew file mode 100644index 000000000..92ff7d119--- /dev/null+++ b/packages/cloud/tests/server/pictures/service.test.ts@@ -0,0 +1,26 @@+import { describe, expect, test } from 'bun:test'++import { pngHeader } from '#cloud-tests/helpers/pictures'+import { CLOUD_PICTURE_MAX_BYTES } from '#cloud/contract'+import { pictureFormat } from '#cloud/server/pictures'+import { utf8ToBytes } from '@noble/hashes/utils.js'++describe('picture format', () => {+ test('keeps PNG and JPEG pictures of a reasonable size', () => {+ expect(pictureFormat(pngHeader(256, 256))).toBe('png')+ const jpeg = new Uint8Array([+ 0xff, 0xd8, 0xff, 0xe0, 0, 16, 0x4a, 0x46, 0x49, 0x46, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 0xff,+ 0xc0, 0, 17, 8, 1, 0, 1, 0, 3, 1, 0x22, 0, 2, 0x11, 1, 3, 0x11, 1, 0xff, 0xd9+ ])+ expect(pictureFormat(jpeg)).toBe('jpeg')+ })++ test('refuses other files, huge sizes, and oversized bytes', () => {+ expect(pictureFormat(utf8ToBytes('<svg xmlns="http://www.w3.org/2000/svg"/>'))).toBeNull()+ expect(pictureFormat(new Uint8Array())).toBeNull()+ expect(pictureFormat(pngHeader(4096, 4096))).toBeNull()+ const padded = new Uint8Array(CLOUD_PICTURE_MAX_BYTES + 1)+ padded.set(pngHeader(256, 256))+ expect(pictureFormat(padded)).toBeNull()+ })+})diff --git a/packages/core/src/canvas/text/ink.ts b/packages/core/src/canvas/text/ink.tsindex d5f2197e0..8cb4fc615 100644--- a/packages/core/src/canvas/text/ink.ts+++ b/packages/core/src/canvas/text/ink.ts@@ -36,13 +36,17 @@ class BandInk {this.y = y}+ /** A quadratic is the cubic whose control points lie two thirds of the way to its own. */quadTo(x1: number, y1: number, x: number, y: number): void {const { x: x0, y: y0 } = this- for (let step = 1; step <= CURVE_STEPS; step++) {- const t = step / CURVE_STEPS- const u = 1 - t- this.lineTo(u * u * x0 + 2 * u * t * x1 + t * t * x, u * u * y0 + 2 * u * t * y1 + t * t * y)- }+ this.cubicTo(+ x0 + (2 / 3) * (x1 - x0),+ y0 + (2 / 3) * (y1 - y0),+ x + (2 / 3) * (x1 - x),+ y + (2 / 3) * (y1 - y),+ x,+ y+ )}cubicTo(x1: number, y1: number, x2: number, y2: number, x: number, y: number): void {diff --git a/packages/docs/development/cloud.md b/packages/docs/development/cloud.mdindex f69a89574..21cf617fb 100644--- a/packages/docs/development/cloud.md+++ b/packages/docs/development/cloud.md@@ -211,7 +211,19 @@ filtered to administrators, suspended accounts, or accounts without two-step sigfor each filter. A person's page shows how they sign in, their workspaces, sessions, and recentsign-ins. Administrators make and remove administrators, sign people out everywhere, suspendwith a reason the activity log keeps, and reset a locked-out person's two-step sign-in, which-removes their authenticator app, recovery codes, and passkeys. Every action asks once more.+removes their authenticator app, recovery codes, and passkeys, and take down a person's picture.+Every action asks once more.++Account pictures live in `user_picture`, one per account, and `user.image` holds the address the+server serves them from, `/api/pictures/:userId/:version`, where the version is the start of the+picture's SHA-256: a new picture is a new address. Responses are cached for one day, so a+picture an administrator removes may stay visible until the cache expires. The+page crops and shrinks a picture to a 256-pixel JPEG; the server accepts PNG or JPEG of at most+256 KB and 1024 pixels a side, reading the type and size from the bytes. A Google picture is+fetched once a sign-in issues its session and kept the same way; one that cannot be fetched leaves+initials, never a link to Google. The server fetches only from Google's picture host and follows no+redirects. Only a provider's sign-in may write `user.image` through Better Auth; an address+sent with email sign-up or a user update is dropped.## Portal@@ -504,6 +516,14 @@ documents, and deleted documents already have their own retention, so a delay wonothing but the name and members. Workspace settings stay in the editor's Members dialog, whichthe desktop app reaches without leaving for a browser.+**2026-10 · Pictures are kept in the database, and Gravatar is not used.** A 256-pixel JPEG is+a few dozen kilobytes. Object storage only hands out short-lived signed links, so pictures there+would need upload tracking, a quota exemption, and a redirect for every picture a page shows; in a+table the server reads the bytes, checks them, and serves them itself. Gravatar would send every+viewer's address and a hash of each person's email to a third party, which a self-hosted server+should not do by default; copying a linked Google picture instead of linking to it follows the+same rule.+**2026-10 · Tables are named for what they hold.** OpenPencil's tables beside Better Auth's had a`cloud_` prefix the rest never had; they lose it, and only a name Better Auth already uses gets aqualifier (`api_rate_limit` beside its `rate_limit`). Migrations that shipped before the renamediff --git a/packages/docs/user-guide/openpencil-cloud.md b/packages/docs/user-guide/openpencil-cloud.mdindex 38c7ffbd4..ee6011bb4 100644--- a/packages/docs/user-guide/openpencil-cloud.md+++ b/packages/docs/user-guide/openpencil-cloud.md@@ -21,7 +21,7 @@ Servers that review new accounts say so before you sign up. Until an administratEach server in **Settings → Cloud** shows who is signed in to it:- **Sign-in expired** keeps your account, so **Sign in** goes back to the same one.-- **Account and security** in the server's **…** menu opens the server's own account pages. See [Your Account](#your-account).+- **Account and security** in the server's **…** menu opens the server's own account pages, as does **Account settings** in the **…** menu beside **OpenPencil Cloud** in Home's sidebar. See [Your Account](#your-account).- **Sign out** ends the session on the server. If the server can't be reached, you stay signed in so you can try again. At the server's own editor address, signing out of that server goes back to its welcome page, unless the server lets you use its editor without an account and you chose to on this browser.- **Disconnect server** signs you out and forgets the server on this device; your documents stay on it, and you can connect again anytime. It warns you when documents still have changes that haven't reached the server, because disconnecting discards them.@@ -31,7 +31,7 @@ The desktop app keeps its sign-in in the system credential store. In the browserA server's account pages have three parts:-- **Profile** changes your name and shows your account ID, which an administrator may ask for. A picture comes from a linked Google or Apple account; without one, your initials stand in. **Change email** sends a link to the new address, and your email changes once you open it. The old address gets a note saying which address is taking over. If you signed in a while ago, the server asks for your password first.+- **Profile** shows your picture, name, and email, and your account ID, which an administrator may ask for. **Upload picture**, beside your picture, takes a PNG, JPEG, WebP, or GIF image; drag and zoom it to choose what shows in the circle, and **Remove**, once you confirm, goes back to your initials. **Change name** opens a dialog for your new name. Signing in with Google uses your Google picture until you upload one. The server keeps every picture itself, so pages never load them from Google or anywhere else. **Change email** sends a link to the new address, and your email changes once you open it. The old address gets a note saying which address is taking over. If you signed in a while ago, the server asks for your password first.- **Sign-in and security** links Google or Apple, changes your password, and sets up two-step sign-in with an authenticator app or passkeys. Recovery codes are shown once: copy or download them before you close the dialog.- **Sessions** lists every browser and desktop app signed in to your account, with when each was last active, and your recent sign-ins. Sign out any session you don't recognize, or all of them except the one you're using.@@ -123,4 +123,3 @@ People who open a link without an account, where the server allows it, join undeWhen your workspace's plan includes AI and the server offers it, the AI assistant can use models through Cloud instead of a key of your own. In **Settings → AI**, add a model, choose **OpenPencil Cloud** as the provider, and pick the workspace whose plan pays for it; the models and their prices come from the server. **OpenPencil Cloud** is listed while you are signed in to the server Home shows.Each request uses the workspace's AI credits for the month. When they run out, the assistant says so and, if the server bills, offers **Manage plan**. Self-hosted servers run their own AI service with their own models and limits ([self-hosting guide](/reference/self-hosting-cloud#ai)).-diff --git a/packages/vue/src/i18n/locales/de/cloud/portal.json b/packages/vue/src/i18n/locales/de/cloud/portal.jsonindex 96e50426a..c9f44c77f 100644--- a/packages/vue/src/i18n/locales/de/cloud/portal.json+++ b/packages/vue/src/i18n/locales/de/cloud/portal.json@@ -111,11 +111,23 @@"activityDescription": "Was Administratoren auf diesem Server getan haben.","detailsSection": "Angaben","detailsSectionDescription": "Andere sehen deinen Namen und dein Bild neben deinen Bearbeitungen und Kommentaren.",- "picture": "Bild",- "pictureFromProvider": "Aus deinem verknüpften Konto",- "pictureInitials": "Deine Initialen, bis du ein Konto mit Bild verknüpfst",+ "uploadPicture": "Bild hochladen",+ "changePicture": "Bild ändern",+ "removePicture": "Entfernen",+ "pictureTitle": "Dein Bild",+ "pictureDescription": "Zieh das Bild und zoome, um festzulegen, was im Kreis zu sehen ist.",+ "pictureZoom": "Zoom",+ "savePicture": "Bild speichern",+ "pictureSaved": "Bild gespeichert",+ "pictureRemoved": "Bild entfernt",+ "removePictureHeading": "Dein Bild entfernen?",+ "removePictureDescription": "An seiner Stelle erscheinen deine Initialen, bis du ein anderes Bild hochlädst.",+ "removePictureConfirm": "Bild entfernen",+ "pictureUnreadable": "Diese Datei ist kein Bild, das die Seite öffnen kann. Wähle ein PNG-, JPEG-, WebP- oder GIF-Bild.","save": "Speichern","nameSaved": "Name gespeichert",+ "changeName": "Namen ändern",+ "changeNameTitle": "Namen ändern","changeEmail": "E-Mail-Adresse ändern","changeEmailTitle": "E-Mail-Adresse ändern","changeEmailDescription": "Wir senden einen Link an die neue Adresse. Bis du ihn öffnest, bleibt {email} deine E-Mail-Adresse.",@@ -253,6 +265,9 @@"resetTwoStep": "Zweistufige Anmeldung zurücksetzen","resetTwoStepHeading": "Zweistufige Anmeldung für {name} zurücksetzen?","resetTwoStepDescription": "Authenticator-App, Wiederherstellungscodes und Passkeys der Person werden entfernt. So kann sie sich mit ihrem Passwort oder einem verknüpften Konto anmelden und alles neu einrichten. Sie erhält eine E-Mail darüber.",+ "removePersonPicture": "Bild entfernen",+ "removePersonPictureHeading": "Bild von {name} entfernen?",+ "removePersonPictureDescription": "An seiner Stelle erscheinen die Initialen der Person. Sie kann ein anderes Bild hochladen.","backToPeople": "Alle Personen","personAccount": "Konto","emailVerified": "Bestätigt",@@ -355,6 +370,7 @@"activityRemovedAdmin": "entzog die Administratorrechte von","activityEmailRetried": "sendete eine E-Mail erneut an","activityTwoStepReset": "setzte die zweistufige Anmeldung zurück für",+ "activityPictureRemoved": "entfernte das Bild von","activityReason": "Grund: {reason}","activityChanged": "änderte","errorTitle": "Das hat nicht funktioniert",@@ -368,6 +384,7 @@"errorAlreadyDecided": "Über diese Anfrage wurde bereits entschieden. Aktualisiere die Seite, um das Ergebnis zu sehen.","errorEmailUnchanged": "Das ist bereits deine E-Mail-Adresse.","errorCurrentSession": "Melde dich ab, um die Sitzung zu beenden, die du gerade nutzt.",+ "errorPictureInvalid": "Der Server kann dieses Bild nicht verwenden. Wähle ein anderes Bild.","passwordResetSent": "Wir haben dir einen Link zum Festlegen eines Passworts gesendet.","repeatPassword": "Passwort wiederholen","errorNameRequired": "Gib deinen Namen ein.",diff --git a/packages/vue/src/i18n/locales/es/cloud/portal.json b/packages/vue/src/i18n/locales/es/cloud/portal.jsonindex 0efb396b8..cab163d17 100644--- a/packages/vue/src/i18n/locales/es/cloud/portal.json+++ b/packages/vue/src/i18n/locales/es/cloud/portal.json@@ -111,11 +111,23 @@"activityDescription": "Lo que han hecho los administradores en este servidor.","detailsSection": "Datos","detailsSectionDescription": "Las personas ven tu nombre y tu foto junto a tus ediciones y comentarios.",- "picture": "Foto",- "pictureFromProvider": "De tu cuenta vinculada",- "pictureInitials": "Tus iniciales, hasta que vincules una cuenta con foto",+ "uploadPicture": "Subir foto",+ "changePicture": "Cambiar imagen",+ "removePicture": "Eliminar",+ "pictureTitle": "Tu foto",+ "pictureDescription": "Arrastra la foto y usa el zoom para elegir lo que se ve en el círculo.",+ "pictureZoom": "Zoom",+ "savePicture": "Guardar foto",+ "pictureSaved": "Foto guardada",+ "pictureRemoved": "Foto eliminada",+ "removePictureHeading": "¿Eliminar tu foto?",+ "removePictureDescription": "En su lugar se mostrarán tus iniciales hasta que subas otra foto.",+ "removePictureConfirm": "Eliminar foto",+ "pictureUnreadable": "Este archivo no es una imagen que la página pueda abrir. Elige una imagen PNG, JPEG, WebP o GIF.","save": "Guardar","nameSaved": "Nombre guardado",+ "changeName": "Cambiar nombre",+ "changeNameTitle": "Cambia tu nombre","changeEmail": "Cambiar correo","changeEmailTitle": "Cambia tu correo","changeEmailDescription": "Enviaremos un enlace a la nueva dirección. {email} seguirá siendo tu correo hasta que lo abras.",@@ -253,6 +265,9 @@"resetTwoStep": "Restablecer la verificación en dos pasos","resetTwoStepHeading": "¿Restablecer la verificación en dos pasos de {name}?","resetTwoStepDescription": "Se eliminan su app de autenticación, sus códigos de recuperación y sus llaves de acceso, para que pueda iniciar sesión con su contraseña o una cuenta vinculada y volver a configurarlos. Recibirá un correo avisándole.",+ "removePersonPicture": "Eliminar foto",+ "removePersonPictureHeading": "¿Eliminar la foto de {name}?",+ "removePersonPictureDescription": "En su lugar se mostrarán sus iniciales. Podrá subir otra foto.","backToPeople": "Todas las personas","personAccount": "Cuenta","emailVerified": "Verificado",@@ -355,6 +370,7 @@"activityRemovedAdmin": "quitó los permisos de administrador a","activityEmailRetried": "reintentó un correo a","activityTwoStepReset": "restableció la verificación en dos pasos de",+ "activityPictureRemoved": "eliminó la foto de","activityReason": "Motivo: {reason}","activityChanged": "cambió","errorTitle": "No ha funcionado",@@ -368,6 +384,7 @@"errorAlreadyDecided": "Alguien ya ha resuelto esta solicitud. Actualiza para verla.","errorEmailUnchanged": "Ese ya es tu correo.","errorCurrentSession": "Cierra sesión para terminar la sesión que estás usando.",+ "errorPictureInvalid": "El servidor no puede usar esta foto. Elige otra imagen.","passwordResetSent": "Te hemos enviado un enlace para establecer una contraseña.","repeatPassword": "Repite la contraseña","errorNameRequired": "Escribe tu nombre.",diff --git a/packages/vue/src/i18n/locales/fr/cloud/portal.json b/packages/vue/src/i18n/locales/fr/cloud/portal.jsonindex 18c1b10e9..9b04d3ccd 100644--- a/packages/vue/src/i18n/locales/fr/cloud/portal.json+++ b/packages/vue/src/i18n/locales/fr/cloud/portal.json@@ -111,11 +111,23 @@"activityDescription": "Les actions des administrateurs sur ce serveur.","detailsSection": "Informations","detailsSectionDescription": "Les autres voient votre nom et votre photo à côté de vos modifications et commentaires.",- "picture": "Photo",- "pictureFromProvider": "Celle de votre compte associé",- "pictureInitials": "Vos initiales, jusqu’à ce que vous associiez un compte avec une photo",+ "uploadPicture": "Importer une photo",+ "changePicture": "Modifier la photo",+ "removePicture": "Supprimer",+ "pictureTitle": "Votre photo",+ "pictureDescription": "Faites glisser la photo et zoomez pour choisir ce qui apparaît dans le cercle.",+ "pictureZoom": "Zoom",+ "savePicture": "Enregistrer la photo",+ "pictureSaved": "Photo enregistrée",+ "pictureRemoved": "Photo supprimée",+ "removePictureHeading": "Supprimer votre photo ?",+ "removePictureDescription": "Vos initiales s’affichent à la place jusqu’à ce que vous importiez une autre photo.",+ "removePictureConfirm": "Supprimer la photo",+ "pictureUnreadable": "Ce fichier n’est pas une image que la page peut ouvrir. Choisissez une image PNG, JPEG, WebP ou GIF.","save": "Enregistrer","nameSaved": "Nom enregistré",+ "changeName": "Modifier le nom",+ "changeNameTitle": "Modifier votre nom","changeEmail": "Modifier l’e-mail","changeEmailTitle": "Modifier votre adresse e-mail","changeEmailDescription": "Nous envoyons un lien à la nouvelle adresse. {email} reste votre adresse jusqu’à ce que vous le suiviez.",@@ -253,6 +265,9 @@"resetTwoStep": "Réinitialiser la connexion en deux étapes","resetTwoStepHeading": "Réinitialiser la connexion en deux étapes de {name} ?","resetTwoStepDescription": "Son app d’authentification, ses codes de récupération et ses clés d’accès sont supprimés : cette personne pourra se connecter avec son mot de passe ou un compte associé et les configurer à nouveau. Elle en est informée par e-mail.",+ "removePersonPicture": "Supprimer la photo",+ "removePersonPictureHeading": "Supprimer la photo de {name} ?",+ "removePersonPictureDescription": "Ses initiales s’affichent à la place. Cette personne pourra importer une autre photo.","backToPeople": "Toutes les personnes","personAccount": "Compte","emailVerified": "Vérifiée",@@ -355,6 +370,7 @@"activityRemovedAdmin": "a retiré les droits d’administrateur à","activityEmailRetried": "a renvoyé un e-mail à","activityTwoStepReset": "a réinitialisé la connexion en deux étapes de",+ "activityPictureRemoved": "a supprimé la photo de","activityReason": "Motif : {reason}","activityChanged": "a modifié","errorTitle": "Cela n’a pas fonctionné",@@ -368,6 +384,7 @@"errorAlreadyDecided": "Quelqu’un a déjà statué sur cette demande. Actualisez pour voir la décision.","errorEmailUnchanged": "C’est déjà votre adresse e-mail.","errorCurrentSession": "Déconnectez-vous pour mettre fin à la session que vous utilisez.",+ "errorPictureInvalid": "Le serveur ne peut pas utiliser cette photo. Choisissez une autre image.","passwordResetSent": "Nous vous avons envoyé par e-mail un lien pour définir un mot de passe.","repeatPassword": "Répétez le mot de passe","errorNameRequired": "Saisissez votre nom.",diff --git a/packages/vue/src/i18n/locales/it/cloud/portal.json b/packages/vue/src/i18n/locales/it/cloud/portal.jsonindex 7ab1e0b68..ba9abe1d4 100644--- a/packages/vue/src/i18n/locales/it/cloud/portal.json+++ b/packages/vue/src/i18n/locales/it/cloud/portal.json@@ -111,11 +111,23 @@"activityDescription": "Le azioni degli amministratori su questo server.","detailsSection": "Dettagli","detailsSectionDescription": "Le persone vedono il tuo nome e la tua immagine accanto alle tue modifiche e ai tuoi commenti.",- "picture": "Immagine",- "pictureFromProvider": "Dal tuo account collegato",- "pictureInitials": "Le tue iniziali, finché non colleghi un account con un’immagine",+ "uploadPicture": "Carica immagine",+ "changePicture": "Cambia immagine",+ "removePicture": "Rimuovi",+ "pictureTitle": "La tua immagine",+ "pictureDescription": "Trascina l’immagine e usa lo zoom per scegliere cosa mostrare nel cerchio.",+ "pictureZoom": "Zoom",+ "savePicture": "Salva immagine",+ "pictureSaved": "Immagine salvata",+ "pictureRemoved": "Immagine rimossa",+ "removePictureHeading": "Rimuovere la tua immagine?",+ "removePictureDescription": "Al suo posto compariranno le tue iniziali finché non carichi un’altra immagine.",+ "removePictureConfirm": "Rimuovi immagine",+ "pictureUnreadable": "Questo file non è un’immagine che la pagina può aprire. Scegli un’immagine PNG, JPEG, WebP o GIF.","save": "Salva","nameSaved": "Nome salvato",+ "changeName": "Cambia nome",+ "changeNameTitle": "Cambia il tuo nome","changeEmail": "Cambia email","changeEmailTitle": "Cambia la tua email","changeEmailDescription": "Inviamo un link al nuovo indirizzo. {email} resta la tua email finché non lo apri.",@@ -253,6 +265,9 @@"resetTwoStep": "Reimposta la verifica in due passaggi","resetTwoStepHeading": "Reimpostare la verifica in due passaggi di {name}?","resetTwoStepDescription": "L’app di autenticazione, i codici di recupero e le passkey vengono rimossi, così potrà accedere con la password o un account collegato e configurarli di nuovo. Riceverà un’email che lo comunica.",+ "removePersonPicture": "Rimuovi immagine",+ "removePersonPictureHeading": "Rimuovere l’immagine di {name}?",+ "removePersonPictureDescription": "Al suo posto compariranno le sue iniziali. Potrà caricare un’altra immagine.","backToPeople": "Tutte le persone","personAccount": "Account","emailVerified": "Verificata",@@ -355,6 +370,7 @@"activityRemovedAdmin": "ha rimosso i diritti di amministratore a","activityEmailRetried": "ha ritentato l’invio di un’email a","activityTwoStepReset": "ha reimpostato la verifica in due passaggi di",+ "activityPictureRemoved": "ha rimosso l’immagine di","activityReason": "Motivo: {reason}","activityChanged": "ha modificato","errorTitle": "Operazione non riuscita",@@ -368,6 +384,7 @@"errorAlreadyDecided": "Qualcuno ha già deciso su questa richiesta. Aggiorna per vederla.","errorEmailUnchanged": "È già la tua email.","errorCurrentSession": "Esci per terminare la sessione che stai usando.",+ "errorPictureInvalid": "Il server non può usare questa immagine. Scegline un’altra.","passwordResetSent": "Ti abbiamo inviato via email un link per impostare una password.","repeatPassword": "Ripeti la password","errorNameRequired": "Inserisci il tuo nome.",diff --git a/packages/vue/src/i18n/locales/ja/cloud/portal.json b/packages/vue/src/i18n/locales/ja/cloud/portal.jsonindex da5effe95..c5eeb79ff 100644--- a/packages/vue/src/i18n/locales/ja/cloud/portal.json+++ b/packages/vue/src/i18n/locales/ja/cloud/portal.json@@ -110,11 +110,23 @@"activityDescription": "このサーバーで管理者が行った操作です。","detailsSection": "詳細","detailsSectionDescription": "あなたの名前と画像は、編集やコメントの横に表示されます。",- "picture": "画像",- "pictureFromProvider": "リンク済みアカウントの画像",- "pictureInitials": "画像のあるアカウントをリンクするまでは、イニシャルを表示します",+ "uploadPicture": "画像をアップロード",+ "changePicture": "画像を変更",+ "removePicture": "削除",+ "pictureTitle": "あなたの画像",+ "pictureDescription": "画像をドラッグしてズームし、円の中に表示する部分を選んでください。",+ "pictureZoom": "ズーム",+ "savePicture": "画像を保存",+ "pictureSaved": "画像を保存しました",+ "pictureRemoved": "画像を削除しました",+ "removePictureHeading": "画像を削除しますか?",+ "removePictureDescription": "別の画像をアップロードするまで、代わりにイニシャルが表示されます。",+ "removePictureConfirm": "画像を削除",+ "pictureUnreadable": "このファイルはページで開ける画像ではありません。PNG、JPEG、WebP、GIFのいずれかの画像を選んでください。","save": "保存","nameSaved": "名前を保存しました",+ "changeName": "名前を変更",+ "changeNameTitle": "名前を変更","changeEmail": "メールアドレスを変更","changeEmailTitle": "メールアドレスを変更","changeEmailDescription": "新しいアドレスにリンクを送信します。リンクを開くまでは {email} がメールアドレスのままです。",@@ -251,6 +263,9 @@"resetTwoStep": "2段階認証をリセット","resetTwoStepHeading": "{name}の2段階認証をリセットしますか?","resetTwoStepDescription": "認証アプリ、リカバリーコード、パスキーが削除されます。本人はパスワードまたはリンク済みアカウントでサインインし、もう一度設定できます。本人にその旨のメールが届きます。",+ "removePersonPicture": "画像を削除",+ "removePersonPictureHeading": "{name}の画像を削除しますか?",+ "removePersonPictureDescription": "代わりにイニシャルが表示されます。本人は別の画像をアップロードできます。","backToPeople": "すべてのユーザー","personAccount": "アカウント","emailVerified": "確認済み",@@ -348,6 +363,7 @@"activityRemovedAdmin": "が管理者権限を削除:","activityEmailRetried": "がメールを再送信:","activityTwoStepReset": "が2段階認証をリセット:",+ "activityPictureRemoved": "が画像を削除:","activityReason": "理由:{reason}","activityChanged": "が変更:","errorTitle": "操作できませんでした",@@ -361,6 +377,7 @@"errorAlreadyDecided": "このリクエストはすでに他の人が対応しました。更新して確認してください。","errorEmailUnchanged": "すでにそのメールアドレスを使用しています。","errorCurrentSession": "使用中のセッションを終了するには、サインアウトしてください。",+ "errorPictureInvalid": "サーバーはこの画像を使用できません。別の画像を選んでください。","passwordResetSent": "パスワードを設定するためのリンクをメールでお送りしました。","repeatPassword": "パスワード(確認)","errorNameRequired": "名前を入力してください。",diff --git a/packages/vue/src/i18n/locales/pl/cloud/portal.json b/packages/vue/src/i18n/locales/pl/cloud/portal.jsonindex 591be8038..ea9dead92 100644--- a/packages/vue/src/i18n/locales/pl/cloud/portal.json+++ b/packages/vue/src/i18n/locales/pl/cloud/portal.json@@ -112,11 +112,23 @@"activityDescription": "Działania administratorów na tym serwerze.","detailsSection": "Szczegóły","detailsSectionDescription": "Inni widzą Twoje imię i zdjęcie obok Twoich zmian i komentarzy.",- "picture": "Zdjęcie",- "pictureFromProvider": "Z połączonego konta",- "pictureInitials": "Twoje inicjały, dopóki nie połączysz konta ze zdjęciem",+ "uploadPicture": "Prześlij zdjęcie",+ "changePicture": "Zmień zdjęcie",+ "removePicture": "Usuń",+ "pictureTitle": "Twoje zdjęcie",+ "pictureDescription": "Przeciągnij zdjęcie i przybliż je, aby wybrać, co widać w kółku.",+ "pictureZoom": "Powiększenie",+ "savePicture": "Zapisz zdjęcie",+ "pictureSaved": "Zapisano zdjęcie",+ "pictureRemoved": "Usunięto zdjęcie",+ "removePictureHeading": "Usunąć Twoje zdjęcie?",+ "removePictureDescription": "W jego miejscu pojawią się Twoje inicjały, dopóki nie prześlesz innego zdjęcia.",+ "removePictureConfirm": "Usuń zdjęcie",+ "pictureUnreadable": "Ten plik nie jest obrazem, który strona może otworzyć. Wybierz obraz PNG, JPEG, WebP lub GIF.","save": "Zapisz","nameSaved": "Zapisano imię",+ "changeName": "Zmień imię",+ "changeNameTitle": "Zmień imię","changeEmail": "Zmień adres e-mail","changeEmailTitle": "Zmień adres e-mail","changeEmailDescription": "Wyślemy link na nowy adres. Do czasu jego otwarcia Twoim adresem pozostaje {email}.",@@ -255,6 +267,9 @@"resetTwoStep": "Zresetuj logowanie dwuetapowe","resetTwoStepHeading": "Zresetować logowanie dwuetapowe: {name}?","resetTwoStepDescription": "Aplikacja uwierzytelniająca, kody odzyskiwania i klucze dostępu tej osoby zostaną usunięte, więc zaloguje się hasłem lub połączonym kontem i skonfiguruje je ponownie. Dostanie o tym e-mail.",+ "removePersonPicture": "Usuń zdjęcie",+ "removePersonPictureHeading": "Usunąć zdjęcie: {name}?",+ "removePersonPictureDescription": "W jego miejscu pojawią się inicjały tej osoby. Może przesłać inne zdjęcie.","backToPeople": "Wszyscy użytkownicy","personAccount": "Konto","emailVerified": "Potwierdzony",@@ -362,6 +377,7 @@"activityRemovedAdmin": "— odebranie uprawnień administratora:","activityEmailRetried": "— ponowna wysyłka e-maila do:","activityTwoStepReset": "— reset logowania dwuetapowego:",+ "activityPictureRemoved": "— usunięcie zdjęcia:","activityReason": "Powód: {reason}","activityChanged": "— zmiana:","errorTitle": "Nie udało się",@@ -375,6 +391,7 @@"errorAlreadyDecided": "Ktoś już rozpatrzył tę prośbę. Odśwież stronę, aby zobaczyć decyzję.","errorEmailUnchanged": "To już jest Twój adres e-mail.","errorCurrentSession": "Aby zakończyć sesję, z której korzystasz, wyloguj się.",+ "errorPictureInvalid": "Serwer nie może użyć tego zdjęcia. Wybierz inny obraz.","passwordResetSent": "Wysłaliśmy Ci link do ustawienia hasła.","repeatPassword": "Powtórz hasło","errorNameRequired": "Wpisz swoje imię.",diff --git a/packages/vue/src/i18n/locales/ru/cloud/portal.json b/packages/vue/src/i18n/locales/ru/cloud/portal.jsonindex b0f06c25d..d60d9a0f8 100644--- a/packages/vue/src/i18n/locales/ru/cloud/portal.json+++ b/packages/vue/src/i18n/locales/ru/cloud/portal.json@@ -112,11 +112,23 @@"activityDescription": "Действия администраторов на этом сервере.","detailsSection": "Сведения","detailsSectionDescription": "Ваше имя и фото видны рядом с вашими правками и комментариями.",- "picture": "Фото",- "pictureFromProvider": "Из привязанного аккаунта",- "pictureInitials": "Ваши инициалы, пока вы не привяжете аккаунт с фото",+ "uploadPicture": "Загрузить фото",+ "changePicture": "Изменить фото",+ "removePicture": "Удалить",+ "pictureTitle": "Ваше фото",+ "pictureDescription": "Перетащите фото и измените масштаб, чтобы выбрать, что будет видно в круге.",+ "pictureZoom": "Масштаб",+ "savePicture": "Сохранить фото",+ "pictureSaved": "Фото сохранено",+ "pictureRemoved": "Фото удалено",+ "removePictureHeading": "Удалить ваше фото?",+ "removePictureDescription": "Вместо него будут видны ваши инициалы, пока вы не загрузите другое фото.",+ "removePictureConfirm": "Удалить фото",+ "pictureUnreadable": "Страница не может открыть этот файл как изображение. Выберите изображение PNG, JPEG, WebP или GIF.","save": "Сохранить","nameSaved": "Имя сохранено",+ "changeName": "Изменить имя",+ "changeNameTitle": "Смена имени","changeEmail": "Изменить почту","changeEmailTitle": "Смена почты","changeEmailDescription": "Мы отправим ссылку на новый адрес. Пока вы не перейдёте по ней, вашей почтой остаётся {email}.",@@ -255,6 +267,9 @@"resetTwoStep": "Сбросить двухэтапный вход","resetTwoStepHeading": "Сбросить двухэтапный вход для {name}?","resetTwoStepDescription": "Приложение-аутентификатор, резервные коды и ключи доступа будут удалены: человек сможет войти по паролю или через привязанный аккаунт и настроить их заново. Он получит письмо об этом.",+ "removePersonPicture": "Удалить фото",+ "removePersonPictureHeading": "Удалить фото у {name}?",+ "removePersonPictureDescription": "Вместо него будут видны инициалы. Человек сможет загрузить другое фото.","backToPeople": "Все пользователи","personAccount": "Аккаунт","emailVerified": "Подтверждена",@@ -362,6 +377,7 @@"activityRemovedAdmin": "— снятие прав администратора:","activityEmailRetried": "— повторная отправка письма:","activityTwoStepReset": "— сброс двухэтапного входа:",+ "activityPictureRemoved": "— удаление фото:","activityReason": "Причина: {reason}","activityChanged": "— изменение:","errorTitle": "Не получилось",@@ -375,6 +391,7 @@"errorAlreadyDecided": "По этой заявке уже приняли решение. Обновите страницу, чтобы его увидеть.","errorEmailUnchanged": "Это и так ваша почта.","errorCurrentSession": "Чтобы завершить текущий сеанс, выйдите из аккаунта.",+ "errorPictureInvalid": "Сервер не может использовать это фото. Выберите другое изображение.","passwordResetSent": "Мы отправили вам ссылку для установки пароля.","repeatPassword": "Повторите пароль","errorNameRequired": "Введите имя.",diff --git a/packages/vue/src/i18n/locales/zh-cn/cloud/portal.json b/packages/vue/src/i18n/locales/zh-cn/cloud/portal.jsonindex d9dff5603..69c594523 100644--- a/packages/vue/src/i18n/locales/zh-cn/cloud/portal.json+++ b/packages/vue/src/i18n/locales/zh-cn/cloud/portal.json@@ -110,11 +110,23 @@"activityDescription": "管理员在此服务器上执行的操作。","detailsSection": "详细信息","detailsSectionDescription": "你的名字和头像会显示在你的编辑和评论旁边。",- "picture": "头像",- "pictureFromProvider": "来自你关联的账号",- "pictureInitials": "在你关联带有头像的账号之前,显示你的姓名首字母",+ "uploadPicture": "上传头像",+ "changePicture": "更换头像",+ "removePicture": "移除",+ "pictureTitle": "你的头像",+ "pictureDescription": "拖动图片并缩放,选择在圆圈中显示的部分。",+ "pictureZoom": "缩放",+ "savePicture": "保存头像",+ "pictureSaved": "头像已保存",+ "pictureRemoved": "头像已移除",+ "removePictureHeading": "移除你的头像?",+ "removePictureDescription": "在你上传其他头像之前,原位置会显示你的姓名首字母。",+ "removePictureConfirm": "移除头像",+ "pictureUnreadable": "页面无法打开这个文件。请选择 PNG、JPEG、WebP 或 GIF 格式的图片。","save": "保存","nameSaved": "名字已保存",+ "changeName": "更改名字",+ "changeNameTitle": "更改你的名字","changeEmail": "更改邮箱","changeEmailTitle": "更改你的邮箱","changeEmailDescription": "我们会向新地址发送链接。在你打开链接之前,{email} 仍是你的邮箱。",@@ -251,6 +263,9 @@"resetTwoStep": "重置两步验证","resetTwoStepHeading": "重置 {name} 的两步验证?","resetTwoStepDescription": "对方的身份验证器应用、恢复码和通行密钥都会被移除,之后可以用密码或关联账号登录并重新设置。对方会收到邮件通知。",+ "removePersonPicture": "移除头像",+ "removePersonPictureHeading": "移除 {name} 的头像?",+ "removePersonPictureDescription": "原位置会显示对方的姓名首字母。对方可以再上传其他头像。","backToPeople": "所有成员","personAccount": "账号","emailVerified": "已验证",@@ -348,6 +363,7 @@"activityRemovedAdmin": "取消了管理员权限:","activityEmailRetried": "重新发送了邮件给","activityTwoStepReset": "重置了两步验证:",+ "activityPictureRemoved": "移除了头像:","activityReason": "原因:{reason}","activityChanged": "更改了","errorTitle": "操作失败",@@ -361,6 +377,7 @@"errorAlreadyDecided": "已有人处理了此申请。请刷新查看。","errorEmailUnchanged": "这已经是你的邮箱了。","errorCurrentSession": "要结束你正在使用的会话,请退出登录。",+ "errorPictureInvalid": "服务器无法使用这张图片。请选择其他图片。","passwordResetSent": "我们已向你发送设置密码的链接。","repeatPassword": "再次输入密码","errorNameRequired": "请输入你的名字。",diff --git a/packages/vue/src/i18n/messages/cloud/portal.ts b/packages/vue/src/i18n/messages/cloud/portal.tsindex 52361d314..d0ee69b4f 100644--- a/packages/vue/src/i18n/messages/cloud/portal.ts+++ b/packages/vue/src/i18n/messages/cloud/portal.ts@@ -143,11 +143,24 @@ export const cloudPortalMessageDefaults = {detailsSection: 'Details',detailsSectionDescription: 'People see your name and picture beside your edits and comments.',- picture: 'Picture',- pictureFromProvider: 'From your linked account',- pictureInitials: 'Your initials, until you link an account that has a picture',+ uploadPicture: 'Upload picture',+ changePicture: 'Change picture',+ removePicture: 'Remove',+ pictureTitle: 'Your picture',+ pictureDescription: 'Drag the picture and zoom to choose what shows in the circle.',+ pictureZoom: 'Zoom',+ savePicture: 'Save picture',+ pictureSaved: 'Picture saved',+ pictureRemoved: 'Picture removed',+ removePictureHeading: 'Remove your picture?',+ removePictureDescription: 'Your initials show in its place until you upload another picture.',+ removePictureConfirm: 'Remove picture',+ pictureUnreadable:+ 'This file isn’t a picture the page can open. Choose a PNG, JPEG, WebP, or GIF image.',save: 'Save',nameSaved: 'Name saved',+ changeName: 'Change name',+ changeNameTitle: 'Change your name',changeEmail: 'Change email',changeEmailTitle: 'Change your email',changeEmailDescription: params(@@ -295,6 +308,10 @@ export const cloudPortalMessageDefaults = {resetTwoStepHeading: params('Reset two-step sign-in for {name}?'),resetTwoStepDescription:'Their authenticator app, recovery codes, and passkeys are removed, so they can sign in with their password or a linked account and set them up again. They get an email saying so.',+ removePersonPicture: 'Remove picture',+ removePersonPictureHeading: params('Remove {name}’s picture?'),+ removePersonPictureDescription:+ 'Their initials show in its place. They can upload another picture.',backToPeople: 'All people',personAccount: 'Account',@@ -389,6 +406,7 @@ export const cloudPortalMessageDefaults = {activityRemovedAdmin: 'removed administrator rights from',activityEmailRetried: 'retried an email to',activityTwoStepReset: 'reset two-step sign-in for',+ activityPictureRemoved: 'removed the picture of',activityReason: params('Reason: {reason}'),activityChanged: 'changed',errorTitle: 'That didn’t work',@@ -402,6 +420,7 @@ export const cloudPortalMessageDefaults = {errorAlreadyDecided: 'Someone already decided this request. Refresh to see it.',errorEmailUnchanged: 'That’s already your email.',errorCurrentSession: 'Sign out to end the session you’re using.',+ errorPictureInvalid: 'The server can’t use this picture. Choose another image.',passwordResetSent: 'We emailed you a link to set a password.'} as constdiff --git a/src/app/cloud-portal/failure.ts b/src/app/cloud-portal/failure.tsindex 895a186d5..0120c5808 100644--- a/src/app/cloud-portal/failure.ts+++ b/src/app/cloud-portal/failure.ts@@ -49,7 +49,8 @@ export function usePortalFailureMessages() {rate_limited: value.failureRateLimited,email_unchanged: value.errorEmailUnchanged,email_change_unavailable: value.emailChangeUnavailable,- current_session: value.errorCurrentSession+ current_session: value.errorCurrentSession,+ picture_invalid: value.errorPictureInvalid}return (error.code && words[error.code]) ?? value.failureUnavailable}diff --git a/src/app/cloud-portal/picture.ts b/src/app/cloud-portal/picture.tsnew file mode 100644index 000000000..88845181b--- /dev/null+++ b/src/app/cloud-portal/picture.ts@@ -0,0 +1,102 @@+import { clamp } from 'es-toolkit'++import { CLOUD_PICTURE_SIZE } from '@open-pencil/cloud/contract'+import type { Size } from '@open-pencil/scene-graph/primitives'++/** How far past filling the frame a picture can be zoomed. */+export const PICTURE_MAX_ZOOM = 4+/** JPEG quality for an uploaded picture, which keeps a 256-pixel photo near 30 KB. */+const PICTURE_QUALITY = 0.9++/**+ * Where a picture sits in a square frame: `zoom` 1 fills the frame with its shorter side, and+ * `x` and `y` place its top-left corner, in frame pixels, never leaving a gap in the frame.+ */+export type PictureCrop = { zoom: number; x: number; y: number }++/** How many frame pixels one picture pixel takes at `zoom`. */+export function pictureScale(picture: Size, frame: number, zoom: number): number {+ return (frame / Math.min(picture.width, picture.height)) * zoom+}++/** `crop` moved back inside the picture, so the frame shows picture everywhere. */+export function clampCrop(picture: Size, frame: number, crop: PictureCrop): PictureCrop {+ const zoom = clamp(crop.zoom, 1, PICTURE_MAX_ZOOM)+ const scale = pictureScale(picture, frame, zoom)+ return {+ zoom,+ x: clamp(crop.x, frame - picture.width * scale, 0),+ y: clamp(crop.y, frame - picture.height * scale, 0)+ }+}++/** The picture centred in the frame at `zoom`. */+export function centredCrop(picture: Size, frame: number, zoom = 1): PictureCrop {+ const scale = pictureScale(picture, frame, zoom)+ return clampCrop(picture, frame, {+ zoom,+ x: (frame - picture.width * scale) / 2,+ y: (frame - picture.height * scale) / 2+ })+}++/** `crop` at a new zoom, keeping the point under the frame's centre where it is. */+export function zoomCrop(+ picture: Size,+ frame: number,+ crop: PictureCrop,+ zoom: number+): PictureCrop {+ const ratio = clamp(zoom, 1, PICTURE_MAX_ZOOM) / crop.zoom+ const centre = frame / 2+ return clampCrop(picture, frame, {+ zoom,+ x: centre - (centre - crop.x) * ratio,+ y: centre - (centre - crop.y) * ratio+ })+}++/** The square of the picture, in its own pixels, that the frame shows. */+export function cropRegion(picture: Size, frame: number, crop: PictureCrop) {+ const scale = pictureScale(picture, frame, crop.zoom)+ return { x: (0 - crop.x) / scale, y: (0 - crop.y) / scale, size: frame / scale }+}++/**+ * The square `region` of `source` as the JPEG the server keeps: 256 pixels a side, on white so+ * a transparent picture keeps its look.+ */+export function encodePicture(+ source: CanvasImageSource,+ region: { x: number; y: number; size: number }+): Promise<Blob> {+ const canvas = document.createElement('canvas')+ canvas.width = CLOUD_PICTURE_SIZE+ canvas.height = CLOUD_PICTURE_SIZE+ const context = canvas.getContext('2d')+ if (!context) return Promise.reject(new Error('The browser can’t draw the picture'))+ context.fillStyle = '#ffffff'+ context.fillRect(0, 0, CLOUD_PICTURE_SIZE, CLOUD_PICTURE_SIZE)+ context.imageSmoothingQuality = 'high'+ context.drawImage(+ source,+ region.x,+ region.y,+ region.size,+ region.size,+ 0,+ 0,+ CLOUD_PICTURE_SIZE,+ CLOUD_PICTURE_SIZE+ )+ return new Promise((resolve, reject) => {+ canvas.toBlob(+ (blob) => {+ if (blob) resolve(blob)+ else reject(new Error('The browser can’t encode the picture'))+ },+ 'image/jpeg',+ PICTURE_QUALITY+ )+ })+}diff --git a/src/app/cloud-portal/toast.ts b/src/app/cloud-portal/toast.tsnew file mode 100644index 000000000..0c97a7c0e--- /dev/null+++ b/src/app/cloud-portal/toast.ts@@ -0,0 +1,34 @@+import { ref } from 'vue'++import type { ToastVariant } from '@/components/ui/feedback/toast'++/** How long a confirmation stays; a failure stays long enough to read. */+const TOAST_DURATION = 4000+const ERROR_TOAST_DURATION = 10000++export type PortalToast = { id: number; message: string; variant: ToastVariant }++const toasts = ref<PortalToast[]>([])+let nextId = 0++function show(message: string, variant: ToastVariant) {+ toasts.value = [+ ...toasts.value.filter((entry) => entry.message !== message),+ { id: ++nextId, message, variant }+ ]+}++/**+ * Short messages the portal shows over the page once a change is done or has failed, the way the+ * editor's toasts do; the editor's own store belongs to its shell, which the portal never loads.+ */+export const portalToast = {+ toasts,+ info: (message: string) => show(message, 'default'),+ error: (message: string) => show(message, 'error'),+ remove(id: number) {+ toasts.value = toasts.value.filter((entry) => entry.id !== id)+ },+ duration: (entry: PortalToast) =>+ entry.variant === 'error' ? ERROR_TOAST_DURATION : TOAST_DURATION+}diff --git a/src/app/cloud/home.ts b/src/app/cloud/home.tsindex d520f9b6d..8463df5d7 100644--- a/src/app/cloud/home.ts+++ b/src/app/cloud/home.ts@@ -1,5 +1,6 @@import { computed } from 'vue'+import { openExternalLink } from '@/app/shell/ui'import { IS_CLOUD_SITE } from '@/constants'import { openCloudConnect } from './connect/flow'@@ -33,6 +34,11 @@ export function useHomeCloud() {serverId: computed(() => signedIn.value?.server.id ?? null),// Signing back in goes straight to the server Home shows; without one, choose a server.connect: () => openCloudConnect({ serverId: homeCloudServer.value?.id }),+ /** The server's own account pages, in the browser. */+ openAccount: () => {+ const server = signedIn.value?.server+ if (server) void openExternalLink(new URL('/account', server.url).href)+ },newWorkspace: () => {const server = signedIn.value?.serverif (server) openNewWorkspace(server.id)diff --git a/src/app/cloud/integration/off/index.ts b/src/app/cloud/integration/off/index.tsindex 4c37db46b..b49824e01 100644--- a/src/app/cloud/integration/off/index.ts+++ b/src/app/cloud/integration/off/index.ts@@ -85,6 +85,7 @@ export function useHomeCloud() {workspaces: computed<WorkspaceSummary[]>(() => []),serverId: computed<string | null>(() => null),connect: noop,+ openAccount: noop,newWorkspace: noop,signOut: () => Promise.resolve()}diff --git a/src/app/cloud/servers/store.ts b/src/app/cloud/servers/store.tsindex a6eacf198..e338f0389 100644--- a/src/app/cloud/servers/store.ts+++ b/src/app/cloud/servers/store.ts@@ -13,7 +13,9 @@ const CLOUD_SERVERS_KEY = 'open-pencil:cloud-servers'const cloudAccountSchema = v.object({id: v.string(),name: v.string(),- email: v.string()+ email: v.string(),+ /** The address of the account's picture on the server; unset shows initials. */+ image: v.optional(v.nullable(v.string()))})const cloudServerSchema = v.object({diff --git a/src/app/cloud/sessions/connection.ts b/src/app/cloud/sessions/connection.tsindex 99424b975..e35ad5514 100644--- a/src/app/cloud/sessions/connection.ts+++ b/src/app/cloud/sessions/connection.ts@@ -116,7 +116,12 @@ async function signedInConnection(account: server.account}}- const account = { id: status.user.userId, name: status.user.name, email: status.user.email }+ const account = {+ id: status.user.userId,+ name: status.user.name,+ email: status.user.email,+ image: status.user.image ?? null+ }rememberCloudAccount(server.id, account)if (status.state !== 'active') {const state = status.state === 'pending' ? 'pending' : 'closed'diff --git a/src/app/home/locations.ts b/src/app/home/locations.tsindex cdaf2b60e..0357d1224 100644--- a/src/app/home/locations.ts+++ b/src/app/home/locations.ts@@ -68,7 +68,7 @@ export function useHomeLocations() {homeLocation.value = fromView(next)},connect: cloud.connect,- accountSettings: () => openSettingsDialog('cloud'),+ openAccount: cloud.openAccount,newWorkspace: cloud.newWorkspace,storageSettings: () => openSettingsDialog('storage'),signOut: cloud.signOutdiff --git a/src/components/cloud-portal/account/PortalEmailDialog.vue b/src/components/cloud-portal/account/PortalFieldDialog.vuesimilarity index 59%rename from src/components/cloud-portal/account/PortalEmailDialog.vuerename to src/components/cloud-portal/account/PortalFieldDialog.vueindex 75ece08d2..238b33907 100644--- a/src/components/cloud-portal/account/PortalEmailDialog.vue+++ b/src/components/cloud-portal/account/PortalFieldDialog.vue@@ -1,6 +1,6 @@<script setup lang="ts">import * as v from 'valibot'-import { computed, ref, watch } from 'vue'+import { ref, useId, watch } from 'vue'import { useCloudPortalMessages } from '@open-pencil/vue/i18n'@@ -13,37 +13,52 @@ import AppAlert from '@/components/ui/feedback/AppAlert.vue'import AppInput from '@/components/ui/input/AppInput.vue'import { portalForm } from '@/theme/cloud-portal/form'-/** Asks for the address an account moves to; the server mails it a link to confirm. */+/**+ * Changes one detail of the account, such as its name or email: the field starts from `initial`,+ * and `schema` checks it and gives the value sent.+ */const {- currentEmail,+ heading,+ description,+ label,+ submitLabel,+ schema,+ initial = '',+ type = 'text',+ autocomplete,+ placeholder,+ maxlength,error = null,saving = false-} = defineProps<{ currentEmail: string; error?: string | null; saving?: boolean }>()+} = defineProps<{+ heading: string+ description: string+ label: string+ submitLabel: string+ schema: v.GenericSchema<string, string>+ initial?: string+ type?: 'text' | 'email'+ autocomplete?: string+ placeholder?: string+ maxlength?: number+ error?: string | null+ saving?: boolean+}>()const open = defineModel<boolean>('open', { default: false })-const emit = defineEmits<{ submit: [email: string] }>()+const emit = defineEmits<{ submit: [value: string] }>()const ui = portalForm()const messages = useCloudPortalMessages()-const email = ref('')+const id = useId()+const value = ref(initial)const invalid = ref<string | null>(null)-watch(open, (value) => {- if (!value) {- email.value = ''- invalid.value = null- }+watch(open, (next) => {+ value.value = next ? initial : ''+ invalid.value = null})-const schema = computed(() =>- v.pipe(- v.string(),- v.trim(),- v.nonEmpty(messages.value.errorEmailRequired),- v.email(messages.value.errorEmailInvalid)- )-)-function submit() {- const result = v.safeParse(schema.value, email.value)+ const result = v.safeParse(schema, value.value)if (!result.success) {invalid.value = result.issues[0].messagereturn@@ -55,23 +70,20 @@ function submit() {<template><AppDialogRoot v-model:open="open" size="sm">- <AppDialogHeader- :heading="messages.changeEmailTitle"- :description="messages.changeEmailDescription({ email: currentEmail })"- :close-label="messages.cancel"- />+ <AppDialogHeader :heading="heading" :description="description" :close-label="messages.cancel" /><form novalidate @submit.prevent="submit"><AppDialogBody :ui="{ body: 'flex flex-col gap-3' }"><AppAlert v-if="error" tone="error" :heading="messages.errorTitle" :description="error" /><div :class="ui.field()">- <label for="portal-new-email" :class="ui.label()">{{ messages.newEmail }}</label>+ <label :for="id" :class="ui.label()">{{ label }}</label><AppInput- id="portal-new-email"- v-model="email"- type="email"- autocomplete="email"+ :id="id"+ v-model="value"+ :type="type"+ :autocomplete="autocomplete"+ :maxlength="maxlength"autofocus- :placeholder="messages.emailPlaceholder"+ :placeholder="placeholder":state="invalid ? 'invalid' : 'idle'"/><p v-if="invalid" :class="ui.error()">{{ invalid }}</p>@@ -80,7 +92,7 @@ function submit() {<AppDialogFooter :ui="{ footer: 'justify-between' }"><AppButton type="button" @click="open = false">{{ messages.cancel }}</AppButton><AppButton type="submit" color="primary" variant="solid" :loading="saving">- {{ messages.sendConfirmation }}+ {{ submitLabel }}</AppButton></AppDialogFooter></form>diff --git a/src/components/cloud-portal/account/PortalPictureDialog.stories.ts b/src/components/cloud-portal/account/PortalPictureDialog.stories.tsnew file mode 100644index 000000000..fdd0a6886--- /dev/null+++ b/src/components/cloud-portal/account/PortalPictureDialog.stories.ts@@ -0,0 +1,57 @@+import type { Meta, StoryObj } from '@storybook/vue3-vite'+import { expect, fn, userEvent, waitFor, within } from 'storybook/test'++import PortalPictureDialog from './PortalPictureDialog.vue'++type Args = { file: File | null; error: string | null; onSave: (picture: Blob) => void }++/** A wide picture, so the crop has room to move sideways. */+const picture = new File(+ [+ '<svg xmlns="http://www.w3.org/2000/svg" width="640" height="400"><rect width="640" height="400" fill="#0ea5e9"/><circle cx="320" cy="170" r="90" fill="#f8fafc"/><rect x="170" y="280" width="300" height="140" rx="70" fill="#f8fafc"/></svg>'+ ],+ 'picture.svg',+ { type: 'image/svg+xml' }+)++const meta = {+ title: 'App/Cloud Portal/Picture',+ args: { file: picture, error: null, onSave: fn() },+ render: (args) => ({+ components: { PortalPictureDialog },+ setup: () => ({ args }),+ template: `+ <PortalPictureDialog+ :open="true"+ :file="args.file"+ :error="args.error"+ @save="args.onSave"+ />`+ })+} satisfies Meta<Args>++export default meta+type Story = StoryObj<typeof meta>++export const Crop: Story = {+ play: async ({ args }) => {+ const page = within(document.body)+ const save = await page.findByRole('button', { name: 'Save picture' })+ await waitFor(() => expect(save).toBeEnabled())+ await userEvent.click(save)+ await waitFor(() => expect(args.onSave).toHaveBeenCalledWith(expect.any(Blob)))+ }+}++export const Unreadable: Story = {+ args: { file: new File(['not a picture'], 'notes.png', { type: 'image/png' }) },+ play: async () => {+ const page = within(document.body)+ await expect(await page.findByText(/isn’t a picture the page can open/)).toBeVisible()+ await expect(page.getByRole('button', { name: 'Save picture' })).toBeDisabled()+ }+}++export const Refused: Story = {+ args: { error: 'The server can’t use this picture. Choose another image.' }+}diff --git a/src/components/cloud-portal/account/PortalPictureDialog.vue b/src/components/cloud-portal/account/PortalPictureDialog.vuenew file mode 100644index 000000000..34ea08505--- /dev/null+++ b/src/components/cloud-portal/account/PortalPictureDialog.vue@@ -0,0 +1,203 @@+<script setup lang="ts">+import { useObjectUrl } from '@vueuse/core'+import { SliderRange, SliderRoot, SliderThumb, SliderTrack } from 'reka-ui'+import { computed, ref, useTemplateRef, watch } from 'vue'++import type { Size } from '@open-pencil/scene-graph/primitives'+import { useCloudPortalMessages } from '@open-pencil/vue/i18n'++import {+ centredCrop,+ clampCrop,+ cropRegion,+ encodePicture,+ PICTURE_MAX_ZOOM,+ pictureScale,+ zoomCrop,+ type PictureCrop+} from '@/app/cloud-portal/picture'+import AppButton from '@/components/ui/button/AppButton.vue'+import AppDialogBody from '@/components/ui/dialog/AppDialogBody.vue'+import AppDialogFooter from '@/components/ui/dialog/AppDialogFooter.vue'+import AppDialogHeader from '@/components/ui/dialog/AppDialogHeader.vue'+import AppDialogRoot from '@/components/ui/dialog/AppDialogRoot.vue'+import AppAlert from '@/components/ui/feedback/AppAlert.vue'++/** The side of the square the picture is placed in, in CSS pixels. */+const FRAME = 240+/** How far an arrow key moves the picture. */+const ARROW_STEP = 8++/**+ * Places a chosen image in the circle people see: drag it or use the arrow keys, and zoom. The+ * page shrinks the result to the size the server keeps before it is sent.+ */+const {+ file,+ saving = false,+ error = null+} = defineProps<{ file: File | null; saving?: boolean; error?: string | null }>()+const open = defineModel<boolean>('open', { default: false })+const emit = defineEmits<{ save: [picture: Blob] }>()++const messages = useCloudPortalMessages()+const url = useObjectUrl(() => file)+const image = useTemplateRef<HTMLImageElement>('image')+const size = ref<Size | null>(null)+const crop = ref<PictureCrop>({ zoom: 1, x: 0, y: 0 })+const unreadable = ref(false)+let drag: { pointerId: number; x: number; y: number; from: PictureCrop } | null = null++watch(url, () => {+ size.value = null+ unreadable.value = false+})++const zoom = computed({+ get: () => [crop.value.zoom],+ set: ([next]) => {+ if (size.value && next !== undefined) {+ crop.value = zoomCrop(size.value, FRAME, crop.value, next)+ }+ }+})+const placement = computed(() => {+ if (!size.value) return undefined+ return {+ width: `${size.value.width * pictureScale(size.value, FRAME, crop.value.zoom)}px`,+ transform: `translate(${crop.value.x}px, ${crop.value.y}px)`+ }+})++function loaded(event: Event) {+ if (!(event.target instanceof HTMLImageElement)) return+ const { naturalWidth: width, naturalHeight: height } = event.target+ // An image with no size of its own, such as an SVG without one, has nothing to crop.+ if (width === 0 || height === 0) {+ unreadable.value = true+ return+ }+ size.value = { width, height }+ crop.value = centredCrop(size.value, FRAME)+}++function move(dx: number, dy: number, from = crop.value) {+ if (!size.value) return+ crop.value = clampCrop(size.value, FRAME, { ...from, x: from.x + dx, y: from.y + dy })+}++function startDrag(event: PointerEvent) {+ if (!(event.currentTarget instanceof HTMLElement)) return+ event.currentTarget.setPointerCapture(event.pointerId)+ drag = { pointerId: event.pointerId, x: event.clientX, y: event.clientY, from: crop.value }+}++function dragTo(event: PointerEvent) {+ if (drag?.pointerId !== event.pointerId) return+ move(event.clientX - drag.x, event.clientY - drag.y, drag.from)+}++function endDrag(event: PointerEvent) {+ if (drag?.pointerId === event.pointerId) drag = null+}++const ARROWS: Record<string, [number, number]> = {+ ArrowLeft: [ARROW_STEP, 0],+ ArrowRight: [-ARROW_STEP, 0],+ ArrowUp: [0, ARROW_STEP],+ ArrowDown: [0, -ARROW_STEP]+}++function nudge(event: KeyboardEvent) {+ const step = ARROWS[event.key]+ if (!step) return+ event.preventDefault()+ move(...step)+}++async function save() {+ if (!image.value || !size.value) return+ try {+ emit('save', await encodePicture(image.value, cropRegion(size.value, FRAME, crop.value)))+ } catch {+ unreadable.value = true+ }+}+</script>++<template>+ <AppDialogRoot v-model:open="open" size="sm">+ <AppDialogHeader+ :heading="messages.pictureTitle"+ :description="messages.pictureDescription"+ :close-label="messages.cancel"+ />+ <AppDialogBody :ui="{ body: 'flex flex-col items-center gap-4' }">+ <AppAlert+ v-if="unreadable || error"+ class="self-stretch"+ tone="error"+ :heading="messages.errorTitle"+ :description="unreadable ? messages.pictureUnreadable : (error ?? undefined)"+ />+ <div+ v-show="!unreadable"+ class="relative size-60 cursor-grab touch-none overflow-hidden rounded bg-canvas outline-none select-none focus-visible:ring-2 focus-visible:ring-accent/50 active:cursor-grabbing"+ tabindex="0"+ role="img"+ :aria-label="messages.pictureDescription"+ @pointerdown="startDrag"+ @pointermove="dragTo"+ @pointerup="endDrag"+ @pointercancel="endDrag"+ @keydown="nudge"+ >+ <img+ v-if="url"+ ref="image"+ :src="url"+ alt=""+ draggable="false"+ class="pointer-events-none absolute top-0 left-0 max-w-none"+ :class="{ invisible: !size }"+ :style="placement"+ @load="loaded"+ @error="unreadable = true"+ />+ <div+ class="pointer-events-none absolute inset-0 rounded-full shadow-[0_0_0_9999px_rgb(0_0_0/0.55)] ring-1 ring-white/40"+ />+ </div>+ <SliderRoot+ v-show="!unreadable"+ v-model="zoom"+ :min="1"+ :max="PICTURE_MAX_ZOOM"+ :step="0.01"+ :disabled="!size"+ :aria-label="messages.pictureZoom"+ class="relative flex w-60 touch-none items-center"+ >+ <SliderTrack class="relative h-1.5 grow overflow-hidden rounded-full bg-hover">+ <SliderRange class="absolute h-full bg-accent" />+ </SliderTrack>+ <SliderThumb+ class="block size-3.5 rounded-full border border-accent bg-panel shadow outline-none focus-visible:ring-2 focus-visible:ring-panel-focus"+ />+ </SliderRoot>+ </AppDialogBody>+ <AppDialogFooter :ui="{ footer: 'justify-between' }">+ <AppButton type="button" @click="open = false">{{ messages.cancel }}</AppButton>+ <AppButton+ type="button"+ color="primary"+ variant="solid"+ :loading="saving"+ :disabled="!size"+ @click="save"+ >+ {{ messages.savePicture }}+ </AppButton>+ </AppDialogFooter>+ </AppDialogRoot>+</template>diff --git a/src/components/cloud-portal/account/PortalProfile.vue b/src/components/cloud-portal/account/PortalProfile.vueindex 8b248be60..1cf0bf8b3 100644--- a/src/components/cloud-portal/account/PortalProfile.vue+++ b/src/components/cloud-portal/account/PortalProfile.vue@@ -1,5 +1,5 @@<script setup lang="ts">-import { computed, ref, watch } from 'vue'+import { useFileDialog } from '@vueuse/core'import { useCloudPortalMessages } from '@open-pencil/vue/i18n'@@ -9,13 +9,10 @@ import SettingsRow from '@/components/settings/layout/SettingsRow.vue'import SettingsSection from '@/components/settings/layout/SettingsSection.vue'import AppButton from '@/components/ui/button/AppButton.vue'import AppCopyField from '@/components/ui/input/AppCopyField.vue'-import AppInput from '@/components/ui/input/AppInput.vue'-import { portalForm } from '@/theme/cloud-portal/form'/**- * How a person appears on a Cloud server: their name, which they change here, their email, which- * changes through a link sent to the new address, the picture a linked account gave them, and- * the account ID an administrator asks for.+ * How a person appears on a Cloud server: their picture, changed beside it, their name and email,+ * each changed in a dialog, and the account ID an administrator asks for.*/const {profile,@@ -33,20 +30,22 @@ const {emailChangeAvailable?: booleanbusy?: boolean}>()-const emit = defineEmits<{ rename: [name: string]; changeEmail: [] }>()+const emit = defineEmits<{+ changeName: []+ changeEmail: []+ choosePicture: [file: File]+ removePicture: []+}>()-const ui = portalForm()const messages = useCloudPortalMessages()-const name = ref(profile.name)-watch(- () => profile.name,- (next) => {- name.value = next- }-)-const renamed = computed(() => {- const value = name.value.trim()- return value.length > 0 && value !== profile.name+const { open: pickPicture, onChange: onPicture } = useFileDialog({+ accept: 'image/png,image/jpeg,image/webp,image/gif',+ multiple: false,+ reset: true+})+onPicture((files) => {+ const file = files?.[0]+ if (file) emit('choosePicture', file)})</script>@@ -54,39 +53,38 @@ const renamed = computed(() => {<div class="flex max-w-2xl flex-col gap-6"><div class="flex items-center gap-3"><AccountAvatar :id="profile.id" :name="profile.name" :image="profile.image" size="lg" />- <div class="min-w-0">+ <div class="min-w-0 flex-1"><p class="truncate text-sm font-semibold text-surface">{{ profile.name }}</p><p class="truncate text-xs text-muted">{{ profile.email }}</p><p class="mt-0.5 text-[11px] text-muted">{{ messages.memberSince({ date: profile.memberSince }) }}</p></div>+ <div class="flex shrink-0 items-center gap-2">+ <AppButton+ v-if="profile.image"+ size="sm"+ variant="ghost"+ :disabled="busy"+ @click="emit('removePicture')"+ >+ {{ messages.removePicture }}+ </AppButton>+ <AppButton size="sm" variant="outline" :disabled="busy" @click="pickPicture()">+ {{ profile.image ? messages.changePicture : messages.uploadPicture }}+ </AppButton>+ </div></div><SettingsSection><template #title>{{ messages.detailsSection }}</template><template #description>{{ messages.detailsSectionDescription }}</template><SettingsGroup>- <form- class="flex flex-col gap-1.5 px-3 py-2.5"- novalidate- @submit.prevent="renamed && emit('rename', name.trim())"- >- <label for="portal-profile-name" :class="ui.label()">{{ messages.name }}</label>- <div class="flex items-center gap-2">- <AppInput- id="portal-profile-name"- v-model="name"- autocomplete="name"- maxlength="100"- :disabled="busy"- :ui="{ root: 'flex-1' }"- />- <AppButton v-if="renamed" type="submit" size="sm" variant="outline" :disabled="busy">- {{ messages.save }}- </AppButton>- </div>- </form>+ <SettingsRow :label="messages.name" :description="profile.name">+ <AppButton size="sm" variant="outline" :disabled="busy" @click="emit('changeName')">+ {{ messages.changeName }}+ </AppButton>+ </SettingsRow><SettingsRow:label="messages.email":description="emailChangeAvailable ? profile.email : messages.emailChangeUnavailable"@@ -101,12 +99,6 @@ const renamed = computed(() => {{{ messages.changeEmail }}</AppButton></SettingsRow>- <SettingsRow- :label="messages.picture"- :description="profile.image ? messages.pictureFromProvider : messages.pictureInitials"- >- <AccountAvatar :id="profile.id" :name="profile.name" :image="profile.image" size="md" />- </SettingsRow></SettingsGroup></SettingsSection>diff --git a/src/components/cloud-portal/console/PortalActivity.vue b/src/components/cloud-portal/console/PortalActivity.vueindex 88fc48b92..0824eacf4 100644--- a/src/components/cloud-portal/console/PortalActivity.vue+++ b/src/components/cloud-portal/console/PortalActivity.vue@@ -22,7 +22,8 @@ const actions = computed<Record<string, string>>(() => ({'user.admin-granted': messages.value.activityMadeAdmin,'user.admin-revoked': messages.value.activityRemovedAdmin,'email.regenerated': messages.value.activityEmailRetried,- 'user.two-step-reset': messages.value.activityTwoStepReset+ 'user.two-step-reset': messages.value.activityTwoStepReset,+ 'user.picture-removed': messages.value.activityPictureRemoved}))</script>diff --git a/src/components/cloud-portal/console/PortalPersonActions.vue b/src/components/cloud-portal/console/PortalPersonActions.vueindex 5fb723316..252cafa62 100644--- a/src/components/cloud-portal/console/PortalPersonActions.vue+++ b/src/components/cloud-portal/console/PortalPersonActions.vue@@ -77,6 +77,12 @@ const confirmation = computed(() => {confirm: words.resetTwoStep,tone: 'danger'},+ 'remove-picture': {+ heading: words.removePersonPictureHeading({ name }),+ description: words.removePersonPictureDescription,+ confirm: words.removePersonPicture,+ tone: 'danger'+ },suspend: {heading: words.suspendHeading({ name }),description: words.suspendDescription,@@ -150,6 +156,13 @@ function confirm() {>{{ messages.resetTwoStep }}</DropdownMenuItem>+ <DropdownMenuItem+ v-if="person.image"+ :class="menuUI.item({ justify: 'start' })"+ @select="ask('remove-picture')"+ >+ {{ messages.removePersonPicture }}+ </DropdownMenuItem><DropdownMenuSeparator :class="menuUI.separator()" /><DropdownMenuItem:class="menuUI.item({ justify: 'start' })"diff --git a/src/components/cloud-portal/layout/PortalToaster.vue b/src/components/cloud-portal/layout/PortalToaster.vuenew file mode 100644index 000000000..5dc4bd7bf--- /dev/null+++ b/src/components/cloud-portal/layout/PortalToaster.vue@@ -0,0 +1,30 @@+<script setup lang="ts">+import { ToastProvider, ToastViewport } from 'reka-ui'++import { useI18n } from '@open-pencil/vue/i18n'++import { portalToast } from '@/app/cloud-portal/toast'+import AppToast from '@/components/ui/feedback/AppToast.vue'++const { common } = useI18n()+</script>++<template>+ <ToastProvider swipe-direction="up">+ <AppToast+ v-for="entry in portalToast.toasts.value"+ :key="entry.id"+ :message="entry.message"+ :variant="entry.variant"+ :duration="portalToast.duration(entry)"+ :copyable="entry.variant === 'error'"+ :copy-label="common.copyMessage"+ :copied-label="common.copiedExclamation"+ :close-label="common.close"+ @close="portalToast.remove(entry.id)"+ />+ <ToastViewport+ class="fixed top-2 left-1/2 z-[9999] flex -translate-x-1/2 flex-col items-center gap-1.5"+ />+ </ToastProvider>+</template>diff --git a/src/components/cloud-portal/sections/ProfileSection.vue b/src/components/cloud-portal/sections/ProfileSection.vueindex cd3e88fe0..12dd6fb9e 100644--- a/src/components/cloud-portal/sections/ProfileSection.vue+++ b/src/components/cloud-portal/sections/ProfileSection.vue@@ -1,5 +1,7 @@<script setup lang="ts">-import { computed, onMounted, ref } from 'vue'+import { fromUint8Array } from 'js-base64'+import * as v from 'valibot'+import { computed, onMounted, ref, watch } from 'vue'import { useRoute, useRouter } from 'vue-router'import { CloudPortalAPIError } from '@open-pencil/cloud/client'@@ -9,15 +11,20 @@ import { usePortal } from '@/app/cloud-portal/context'import { usePortalFailureMessages } from '@/app/cloud-portal/failure'import { portalURL } from '@/app/cloud-portal/navigation'import { usePortalAction, usePortalLoad } from '@/app/cloud-portal/state'+import { portalToast } from '@/app/cloud-portal/toast'import { useDateFormat } from '@/app/i18n/date'+import AppConfirmationDialog from '@/components/ui/dialog/AppConfirmationDialog.vue'import AppAlert from '@/components/ui/feedback/AppAlert.vue'-import PortalEmailDialog from '../account/PortalEmailDialog.vue'+import PortalFieldDialog from '../account/PortalFieldDialog.vue'import PortalPasswordDialog from '../account/PortalPasswordDialog.vue'+import PortalPictureDialog from '../account/PortalPictureDialog.vue'import PortalProfile from '../account/PortalProfile.vue'/** The query the email confirmation link comes back with. */const EMAIL_CONFIRMED = 'email-confirmed'+/** The longest name the server keeps. */+const NAME_MAX_LENGTH = 100/*** The signed-in person's name, email, and picture. A new email is confirmed from the new@@ -52,15 +59,62 @@ const profile = computed(() => {}: null})-const notice = ref<string | null>(null)+const nameOpen = ref(false)+const nameSchema = computed(() =>+ v.pipe(+ v.string(),+ v.trim(),+ v.nonEmpty(messages.value.errorNameRequired),+ v.maxLength(NAME_MAX_LENGTH)+ )+)+const emailSchema = computed(() =>+ v.pipe(+ v.string(),+ v.trim(),+ v.nonEmpty(messages.value.errorEmailRequired),+ v.email(messages.value.errorEmailInvalid)+ )+)const rename = usePortalAction(async (name: string) => {- notice.value = null- await portal.api.updateProfile(name)+ if (name !== profile.value?.name) {+ await portal.api.updateProfile(name)+ await Promise.all([loaded.reload(), portal.refreshAccount()])+ portalToast.info(messages.value.nameSaved)+ }+ nameOpen.value = false+})++function openName() {+ rename.clear()+ nameOpen.value = true+}++const pictureFile = ref<File | null>(null)+const pictureOpen = ref(false)++function choosePicture(file: File) {+ savePicture.clear()+ pictureFile.value = file+ pictureOpen.value = true+}++const savePicture = usePortalAction(async (picture: Blob) => {+ await portal.api.uploadPicture(fromUint8Array(new Uint8Array(await picture.arrayBuffer())))+ pictureOpen.value = falseawait Promise.all([loaded.reload(), portal.refreshAccount()])- notice.value = messages.value.nameSaved+ portalToast.info(messages.value.pictureSaved)})+const removeOpen = ref(false)+const removePicture = usePortalAction(async () => {+ await portal.api.removePicture()+ await Promise.all([loaded.reload(), portal.refreshAccount()])+ portalToast.info(messages.value.pictureRemoved)+})+watch(removePicture.error, (failure) => failure && portalToast.error(failure))+const emailOpen = ref(false)const passwordOpen = ref(false)/** The address waiting for a fresh sign-in before it can be asked for. */@@ -70,11 +124,10 @@ async function requestEmail(email: string) {await portal.api.changeEmail(email, portalURL(`/account?${EMAIL_CONFIRMED}`))emailOpen.value = falsepasswordOpen.value = false- notice.value = messages.value.emailChangeSent({ email })+ portalToast.info(messages.value.emailChangeSent({ email }))}const changeEmail = usePortalAction(async (email: string) => {- notice.value = nulltry {await requestEmail(email)} catch (error) {@@ -104,10 +157,11 @@ const busy = computed(() =>loaded.loading.value ||rename.busy.value ||+ savePicture.busy.value ||+ removePicture.busy.value ||changeEmail.busy.value ||confirmPassword.busy.value)-const error = computed(() => rename.error.value ?? loaded.error.value)function openEmail() {changeEmail.clear()@@ -119,26 +173,71 @@ onMounted(async () => {await router.replace({ query: {} })await portal.refreshAccount()const email = portal.account.value?.user.email- if (email) notice.value = messages.value.emailChanged({ email })+ if (email) portalToast.info(messages.value.emailChanged({ email }))})</script><template>- <div class="flex flex-col gap-4">- <AppAlert v-if="error" tone="error" :heading="messages.errorTitle" :description="error" />- <AppAlert v-if="notice" tone="success" :heading="notice" />+ <div class="flex max-w-2xl flex-col gap-4">+ <AppAlert+ v-if="loaded.error.value"+ tone="error"+ :heading="messages.errorTitle"+ :description="loaded.error.value"+ /><PortalProfilev-if="profile":profile="profile":email-change-available="loaded.data.value?.profile.emailChangeAvailable":busy="busy"- @rename="rename.run"+ @change-name="openName"@change-email="openEmail"+ @choose-picture="choosePicture"+ @remove-picture="removeOpen = true"+ />+ <AppConfirmationDialog+ v-model:open="removeOpen"+ tone="danger"+ :heading="messages.removePictureHeading"+ :description="messages.removePictureDescription"+ :cancel-label="messages.cancel"+ :confirm-label="messages.removePictureConfirm"+ :confirm-loading="removePicture.busy.value"+ @confirm="removePicture.run()"+ />+ <PortalPictureDialog+ v-model:open="pictureOpen"+ :file="pictureFile"+ :saving="savePicture.busy.value"+ :error="savePicture.error.value"+ @save="savePicture.run"+ />+ <PortalFieldDialog+ v-if="profile"+ v-model:open="nameOpen"+ :heading="messages.changeNameTitle"+ :description="messages.detailsSectionDescription"+ :label="messages.name"+ :submit-label="messages.save"+ :schema="nameSchema"+ :initial="profile.name"+ autocomplete="name"+ :maxlength="NAME_MAX_LENGTH"+ :error="rename.error.value"+ :saving="rename.busy.value"+ @submit="rename.run"/>- <PortalEmailDialog+ <PortalFieldDialogv-if="profile"v-model:open="emailOpen"- :current-email="profile.email"+ :heading="messages.changeEmailTitle"+ :description="messages.changeEmailDescription({ email: profile.email })"+ :label="messages.newEmail"+ :submit-label="messages.sendConfirmation"+ :schema="emailSchema"+ type="email"+ autocomplete="email"+ :placeholder="messages.emailPlaceholder":error="changeEmail.error.value":saving="busy"@submit="changeEmail.run"diff --git a/src/components/cloud-portal/sections/SecuritySection.vue b/src/components/cloud-portal/sections/SecuritySection.vueindex aeaf130a6..8a1f19e05 100644--- a/src/components/cloud-portal/sections/SecuritySection.vue+++ b/src/components/cloud-portal/sections/SecuritySection.vue@@ -7,6 +7,7 @@ import { usePortal } from '@/app/cloud-portal/context'import { usePortalFailureMessages } from '@/app/cloud-portal/failure'import { portalURL } from '@/app/cloud-portal/navigation'import { usePortalAction, usePortalLoad } from '@/app/cloud-portal/state'+import { portalToast } from '@/app/cloud-portal/toast'import { formatDate } from '@/app/i18n/date'import AppAlert from '@/components/ui/feedback/AppAlert.vue'import { useHeldContent } from '@/components/ui/overlay/held'@@ -34,7 +35,6 @@ const security = usePortalLoad(async () => {const methods = computed(() => security.data.value?.methods ?? null)const mfa = computed(() => security.data.value?.mfa ?? null)const passkeys = computed(() => security.data.value?.passkeys ?? [])-const notice = ref<string | null>(null)type PasswordStep =| 'change'@@ -70,7 +70,6 @@ const minimum = computed(/** One change from the page, then what the page shows read again. */const change = usePortalAction(async (work: () => Promise<unknown>) => {- notice.value = nullawait work()await security.reload()})@@ -174,7 +173,7 @@ function changePassword() {if (!email) returnvoid change.run(async () => {const result = await portal.auth.requestPasswordReset(email, portalURL('/auth/reset-password'))- if (result.ok) notice.value = messages.value.passwordResetSent+ if (result.ok) portalToast.info(messages.value.passwordResetSent)else change.fail(failures.failure(result.failure))})}@@ -202,9 +201,8 @@ function addPasskey() {</script><template>- <div class="flex flex-col gap-4">+ <div class="flex max-w-2xl flex-col gap-4"><AppAlert v-if="error" tone="error" :heading="messages.errorTitle" :description="error" />- <AppAlert v-if="notice" tone="success" :heading="notice" /><PortalAccountSecurityv-if="methods && mfa":methods="linkedMethods"diff --git a/src/components/cloud-portal/sections/people.ts b/src/components/cloud-portal/sections/people.tsindex acfa3faf1..7c23e559c 100644--- a/src/components/cloud-portal/sections/people.ts+++ b/src/components/cloud-portal/sections/people.ts@@ -41,6 +41,7 @@ export function personAction('remove-admin': () => api.setAdmin(person.id, false),'sign-out': () => api.userAction('revoke-sessions', person.id),'reset-two-step': () => api.userAction('reset-two-step', person.id),+ 'remove-picture': () => api.userAction('remove-picture', person.id),suspend: () => api.userAction('ban', person.id, reason),restore: () => api.userAction('unban', person.id)}diff --git a/src/components/cloud-portal/types.ts b/src/components/cloud-portal/types.tsindex 063dad8c3..346ea2e31 100644--- a/src/components/cloud-portal/types.ts+++ b/src/components/cloud-portal/types.ts@@ -50,6 +50,7 @@ export type PortalPersonAction =| 'remove-admin'| 'sign-out'| 'reset-two-step'+ | 'remove-picture'| 'suspend'| 'restore'diff --git a/src/components/home/HomeWorkspace.vue b/src/components/home/HomeWorkspace.vueindex 0adb24ff7..b60260196 100644--- a/src/components/home/HomeWorkspace.vue+++ b/src/components/home/HomeWorkspace.vue@@ -189,7 +189,7 @@ function formattedDate(updatedAt: string): string {:storage="sidebarStorage"@select="places.select"@connect="places.connect"- @account-settings="places.accountSettings"+ @open-account="places.openAccount"@storage-settings="places.storageSettings"@switch-server="places.connect"@new-workspace="places.newWorkspace"diff --git a/src/components/home/cloud/types.ts b/src/components/home/cloud/types.tsindex 6b73b9792..05c883c8a 100644--- a/src/components/home/cloud/types.ts+++ b/src/components/home/cloud/types.ts@@ -9,6 +9,7 @@ export type HomeCloudAccount = {id: stringname: stringemail: string+ image?: string | null/** The Cloud server's host, such as `cloud.openpencil.dev`. */host: string}diff --git a/src/components/home/sidebar/HomeSidebar.vue b/src/components/home/sidebar/HomeSidebar.vueindex bfc61edb3..fb886b53c 100644--- a/src/components/home/sidebar/HomeSidebar.vue+++ b/src/components/home/sidebar/HomeSidebar.vue@@ -12,6 +12,7 @@ import { computed } from 'vue'import { useCloudMessages } from '@open-pencil/vue/i18n'+import AccountAvatar from '@/components/presence/AccountAvatar.vue'import IconButton from '@/components/ui/button/IconButton.vue'import { menu } from '@/components/ui/menu/menu'import Tip from '@/components/ui/overlay/Tip.vue'@@ -44,7 +45,7 @@ const {const emit = defineEmits<{select: [location: HomeLocation]connect: []- accountSettings: []+ openAccount: []storageSettings: []switchServer: []newWorkspace: []@@ -98,14 +99,20 @@ const workspaceLocations = computed(() =>:side-offset="4":class="[menuUI.content(), 'w-56']">- <DropdownMenuLabel :class="menuUI.label()">- {{ account.email }} · {{ account.host }}+ <DropdownMenuLabel :class="[menuUI.label(), 'flex items-center gap-2 pb-1.5']">+ <AccountAvatar :id="account.id" :name="account.name" :image="account.image" />+ <span class="min-w-0">+ <span class="block truncate text-xs text-surface">{{ account.name }}</span>+ <span class="block truncate">{{ account.email }}</span>+ <span class="block truncate">{{ account.host }}</span>+ </span></DropdownMenuLabel>+ <DropdownMenuSeparator :class="menuUI.separator()" /><DropdownMenuItem:class="menuUI.item({ justify: 'start' })"- @select="emit('accountSettings')"+ @select="emit('openAccount')">- <icon-lucide-settings-2 :class="menuUI.icon()" />+ <icon-lucide-external-link :class="menuUI.icon()" />{{ t.homeAccountSettings }}</DropdownMenuItem><DropdownMenuItemdiff --git a/src/components/settings/cloud/CloudSettingsPanel.vue b/src/components/settings/cloud/CloudSettingsPanel.vueindex 370e518f6..58d411c59 100644--- a/src/components/settings/cloud/CloudSettingsPanel.vue+++ b/src/components/settings/cloud/CloudSettingsPanel.vue@@ -117,7 +117,11 @@ const title = (server: CloudServerEntry) =>{{ t.settingsAccessClosed }}</p><p v-else-if="server.account && server.session === 'signed-in'" :class="ui.account()">- <AccountAvatar :id="server.account.id" :name="server.account.name" />+ <AccountAvatar+ :id="server.account.id"+ :name="server.account.name"+ :image="server.account.image ?? null"+ /><span :class="ui.accountText()">{{ server.account.name }} · {{ server.account.email }}</span>diff --git a/src/components/settings/cloud/types.ts b/src/components/settings/cloud/types.tsindex a73c0c232..a6c5f2648 100644--- a/src/components/settings/cloud/types.ts+++ b/src/components/settings/cloud/types.ts@@ -3,7 +3,7 @@ export type CloudServerEntry = {id: stringhost: stringkind: 'official' | 'self-hosted'- account: { id: string; name: string; email: string } | null+ account: { id: string; name: string; email: string; image?: string | null } | null/** `expired` keeps the account so the person can sign back in to the same one. */session: 'signed-in' | 'pending' | 'closed' | 'expired' | 'signed-out'/** The server whose workspaces Home shows. */diff --git a/src/views/cloud/CloudPortalApp.vue b/src/views/cloud/CloudPortalApp.vueindex c8a0a4d61..17249b471 100644--- a/src/views/cloud/CloudPortalApp.vue+++ b/src/views/cloud/CloudPortalApp.vue@@ -2,10 +2,12 @@import { RouterView } from 'vue-router'import { usePortalTheme } from '@/app/cloud-portal/theme'+import PortalToaster from '@/components/cloud-portal/layout/PortalToaster.vue'usePortalTheme()</script><template><RouterView />+ <PortalToaster /></template>diff --git a/tests/app/cloud-portal/picture.test.ts b/tests/app/cloud-portal/picture.test.tsnew file mode 100644index 000000000..ddba340df--- /dev/null+++ b/tests/app/cloud-portal/picture.test.ts@@ -0,0 +1,39 @@+import { describe, expect, test } from 'bun:test'++import {+ centredCrop,+ clampCrop,+ cropRegion,+ PICTURE_MAX_ZOOM,+ zoomCrop+} from '@/app/cloud-portal/picture'++const FRAME = 240+const LANDSCAPE = { width: 800, height: 400 }++describe('picture crop', () => {+ test('starts centred with the shorter side filling the frame', () => {+ const crop = centredCrop(LANDSCAPE, FRAME)+ expect(crop).toEqual({ zoom: 1, x: -120, y: 0 })+ expect(cropRegion(LANDSCAPE, FRAME, crop)).toEqual({ x: 200, y: 0, size: 400 })+ })++ test('never leaves a gap in the frame', () => {+ expect(clampCrop(LANDSCAPE, FRAME, { zoom: 1, x: 50, y: 30 })).toEqual({ zoom: 1, x: 0, y: 0 })+ expect(clampCrop(LANDSCAPE, FRAME, { zoom: 1, x: -1000, y: -30 })).toEqual({+ zoom: 1,+ x: -240,+ y: 0+ })+ expect(clampCrop(LANDSCAPE, FRAME, { zoom: 9, x: 0, y: 0 }).zoom).toBe(PICTURE_MAX_ZOOM)+ })++ test('zooms around the middle of the frame', () => {+ const zoomed = zoomCrop(LANDSCAPE, FRAME, centredCrop(LANDSCAPE, FRAME), 2)+ expect(zoomed).toEqual({ zoom: 2, x: -360, y: -120 })+ const region = cropRegion(LANDSCAPE, FRAME, zoomed)+ expect(region.x + region.size / 2).toBe(400)+ expect(region.y + region.size / 2).toBe(200)+ expect(region.size).toBe(200)+ })+})diff --git a/tests/app/cloud/sessions/connection.test.ts b/tests/app/cloud/sessions/connection.test.tsindex 4fe4ddc13..483aa9823 100644--- a/tests/app/cloud/sessions/connection.test.ts+++ b/tests/app/cloud/sessions/connection.test.ts@@ -67,7 +67,8 @@ describe('Cloud connections', () => {expect(cloudServers.value[0]?.account).toEqual({id: 'user-1',name: 'Ada',- email: '[email protected]'+ email: '[email protected]',+ image: null})})diff --git a/tools/checks/i18n/mixed-script-baseline.txt b/tools/checks/i18n/mixed-script-baseline.txtindex f6e39123c..5eaaa486f 100644--- a/tools/checks/i18n/mixed-script-baseline.txt+++ b/tools/checks/i18n/mixed-script-baseline.txt@@ -525,6 +525,7 @@ ja:cloudPortal.welcomeTitleja:cloudPortal.accountIdja:cloudPortal.desktopAppja:cloudPortal.methodDesktop+ja:cloudPortal.pictureUnreadablezh-cn:cloud.connectHeadingzh-cn:cloud.connectServerDescriptionzh-cn:cloud.officialDescription@@ -546,6 +547,7 @@ zh-cn:cloudPortal.accountIdzh-cn:cloudPortal.accountIdDescriptionzh-cn:cloudPortal.desktopAppzh-cn:cloudPortal.methodDesktop+zh-cn:cloudPortal.pictureUnreadableja:ai.cloudAIUnavailableja:ai.cloudAINoWorkspaceja:ai.chatCloudCreditsExhausteddiff --git a/tools/checks/i18n/translation-baseline.txt b/tools/checks/i18n/translation-baseline.txtindex 4ce61e519..52035c46d 100644--- a/tools/checks/i18n/translation-baseline.txt+++ b/tools/checks/i18n/translation-baseline.txt@@ -387,6 +387,7 @@ es:cloudPortal.workspaceRoleEditores:cloudPortal.deploymentOfficiales:cloudPortal.emailTransportSMTPes:cloudPortal.emailTransportCloudflare+es:cloudPortal.pictureZoomit:cloudPortal.productNameit:cloudPortal.emailit:cloudPortal.password@@ -405,6 +406,7 @@ it:cloudPortal.deploymentSelfHostedit:cloudPortal.emailTransportSMTPit:cloudPortal.emailTransportCloudflareit:cloudPortal.emailKindOther+it:cloudPortal.pictureZoomde:cloudPortal.productNamede:cloudPortal.namede:cloudPortal.sectionServer@@ -419,6 +421,7 @@ de:cloudPortal.serverSectionde:cloudPortal.deploymentOfficialde:cloudPortal.emailTransportSMTPde:cloudPortal.emailTransportCloudflare+de:cloudPortal.pictureZoomfr:cloudPortal.productNamefr:cloudPortal.providerGooglefr:cloudPortal.providerApple@@ -428,6 +431,7 @@ fr:cloudPortal.documentsfr:cloudPortal.deploymentOfficialfr:cloudPortal.emailTransportSMTPfr:cloudPortal.emailTransportCloudflare+fr:cloudPortal.pictureZoomja:cloudPortal.productNameja:cloudPortal.emailPlaceholderja:cloudPortal.providerGoogle