AI-native design editor. Open-source Figma alternative.
feat: add Cloud account pages, admin person pages, and workspace member tabs (#1458)
Danila Poyarkov9d5c7e323bf1
diff --git a/bun.lock b/bun.lockindex cecbed25d..439ad752c 100644--- a/bun.lock+++ b/bun.lock@@ -221,6 +221,7 @@"@vue-email/components": "^0.0.21","@vue-email/render": "^0.0.9","better-auth": "1.7.7",+ "bowser": "^2.14.1","es-toolkit": "^1.52.0","fflate": "^0.8.3","hono": "^4.13.13",diff --git a/changes/1458/added.md b/changes/1458/added.mdnew file mode 100644index 000000000..0a51d5858--- /dev/null+++ b/changes/1458/added.md@@ -0,0 +1 @@+- A Cloud server's account pages add **Profile**, to change your name and, through a link sent to the new address, your email, and **Sessions**, which lists where your account is signed in and its recent sign-ins and signs out any of them. The server emails you about a sign-in from a new address and about changes to two-step sign-in. Administrators filter and page through people, open a page for each account, reset a locked-out person's two-step sign-in, and give a reason when suspending someone. A workspace's **Members** dialog splits into Members, Invited, and Settings tabs, showing who sent each invitation and when it expires, with **Resend**.diff --git a/packages/cloud/AGENTS.md b/packages/cloud/AGENTS.mdindex d5582ff31..bb8c5914f 100644--- a/packages/cloud/AGENTS.md+++ b/packages/cloud/AGENTS.md@@ -10,6 +10,10 @@ Optional, self-hostable backend; the design is in `packages/docs/development/clo## Data and security+- Sign-ins are recorded by the `accountActivity` Better Auth plugin from the hook context's `newSession`, never by parsing tokens from responses (`src/server/auth/activity.ts`).+- 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`).- 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`).@@ -45,6 +49,6 @@ Optional, self-hostable backend; the design is in `packages/docs/development/clo## Tests-- Unit tests mirror `src` under `tests/{ai-relay,client,contract,runtime,server}`; integration tests mirror `src` under `tests/integration` and run on PGlite through `tests/helpers/database.ts`; `tests/e2e` holds Docker Compose runners that `test` never starts.+- Unit tests mirror `src` under `tests/{ai-relay,client,contract,email,runtime,server}`; integration tests mirror `src` under `tests/integration` and run on PGlite through `tests/helpers/database.ts`; `tests/e2e` holds Docker Compose runners that `test` never starts.- Tests import source through `#cloud/*` and helpers through `#cloud-tests/*`, and read responses with `responseJSON` from `tests/helpers/response.ts`.- `bun run test:cloud` type-checks the package and runs unit and integration suites.diff --git a/packages/cloud/package.json b/packages/cloud/package.jsonindex fa6af6efd..c9a357ba8 100644--- a/packages/cloud/package.json+++ b/packages/cloud/package.json@@ -58,7 +58,7 @@"ai-relay": "bun src/runtime/node/ai-relay/main.ts","check": "bun run typecheck && bun run test && bun run build","test": "bun run test:unit && bun run test:integration",- "test:unit": "bun test tests/ai-relay tests/client tests/contract tests/runtime tests/server",+ "test:unit": "bun test tests/ai-relay tests/client tests/contract tests/email tests/runtime tests/server","test:integration": "bun test --max-concurrency 8 tests/integration","test:e2e": "bun tests/e2e/run.ts","test:e2e:garage": "bun tests/e2e/garage.ts",@@ -84,6 +84,7 @@"@vue-email/components": "^0.0.21","@vue-email/render": "^0.0.9","better-auth": "1.7.7",+ "bowser": "^2.14.1","es-toolkit": "^1.52.0","fflate": "^0.8.3","hono": "^4.13.13",diff --git a/packages/cloud/src/admin/api/routes.ts b/packages/cloud/src/admin/api/routes.tsindex 00bae84a8..e19ae97f5 100644--- a/packages/cloud/src/admin/api/routes.ts+++ b/packages/cloud/src/admin/api/routes.ts@@ -11,6 +11,7 @@ import {parseUserRoleMutation} from '#cloud/admin/schema'import type { AdminUserService } from '#cloud/admin/users/service'+import { cloudAdminUserFilterSchema } from '#cloud/contract'import type { CloudAPIEnvironment } from '#cloud/server/api'import type { CloudAuthAdapter } from '#cloud/server/auth'import type { CloudDatabase } from '#cloud/server/db'@@ -26,10 +27,17 @@ const parseEnrollmentQuery = (input: unknown) =>v.parse(v.object({ status: v.optional(enrollmentStatusSchema) }), input)const parseUserQuery = (input: unknown) =>v.parse(- v.object({ search: v.optional(v.string()), limit: countSchema, offset: countSchema }),+ v.object({+ search: v.optional(v.string()),+ filter: v.optional(cloudAdminUserFilterSchema),+ limit: countSchema,+ offset: countSchema+ }),input)const parseLimitQuery = (input: unknown) => v.parse(v.object({ limit: countSchema }), input)+/** Accounts are named by UUID; anything else names no one, rather than failing the query. */+const accountIdSchema = v.pipe(v.string(), v.uuid())export type CloudAdminServices = {email: AdminEmailService@@ -126,15 +134,22 @@ export function createCloudAdminRoutes()}))- .get('/users', validatedQuery(parseUserQuery), async (context) => {- const query = context.req.valid('query')- return context.json(- await services.users.list(context.req.raw.headers, {- searchValue: query.search,- limit: query.limit ?? 100,- offset: query.offset ?? 0- })- )+ .get('/users', validatedQuery(parseUserQuery), async (context) =>+ context.json(await services.users.list(context.req.valid('query')))+ )+ .get('/users/:id', async (context) => {+ const id = context.req.param('id')+ const detail = v.is(accountIdSchema, id) ? await services.users.detail(id) : null+ 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/ban', validatedJSON(parseUserMutation), async (context) => {const input = context.req.valid('json')diff --git a/packages/cloud/src/admin/audit/service.ts b/packages/cloud/src/admin/audit/service.tsindex de7562709..def73dd22 100644--- a/packages/cloud/src/admin/audit/service.ts+++ b/packages/cloud/src/admin/audit/service.ts@@ -1,17 +1,65 @@import { ADMIN_LIST_MAXIMUM } from '#cloud/admin/schema'import type { CloudDatabase } from '#cloud/server/db'-import { clamp } from 'es-toolkit'+import { clamp, uniq } from 'es-toolkit'import type { Kysely } from 'kysely'+import * as v from 'valibot'++const uuidSchema = v.pipe(v.string(), v.uuid())+const isUUID = (value: string) => v.is(uuidSchema, value)export function createAdminAuditService(database: Kysely<CloudDatabase>) {return {+ /** The newest events, each with its actor's and subject's names while the server knows them. */async list(limit = 100) {- return database- .selectFrom('cloudAdminAuditEvent')+ const events = await database+ .selectFrom('adminAuditEvent').selectAll().orderBy('createdAt', 'desc').limit(clamp(limit, 1, ADMIN_LIST_MAXIMUM)).execute()+ // Accounts and requests are named by UUID; anything else is not looked up.+ const userIds = uniq(+ events.flatMap((event) =>+ event.subjectType === 'user' ? [event.actorUserId, event.subjectId] : [event.actorUserId]+ )+ ).filter(isUUID)+ const enrollmentIds = uniq(+ events.flatMap((event) => (event.subjectType === 'enrollment' ? [event.subjectId] : []))+ ).filter(isUUID)+ const [users, enrollments] = await Promise.all([+ userIds.length+ ? database.selectFrom('user').select(['id', 'name']).where('id', 'in', userIds).execute()+ : [],+ enrollmentIds.length+ ? database+ .selectFrom('enrollment')+ .select(['id', 'name', 'emailNormalized'])+ .where('id', 'in', enrollmentIds)+ .execute()+ : []+ ])+ const names = new Map(users.map((user) => [user.id, user.name]))+ const requesters = new Map(+ enrollments.map((enrollment) => [+ enrollment.id,+ enrollment.name ?? enrollment.emailNormalized+ ])+ )+ return events.map((event) => ({+ id: event.id,+ actor: { id: event.actorUserId, name: names.get(event.actorUserId) ?? null },+ action: event.action,+ subject: {+ type: event.subjectType,+ id: event.subjectId,+ name:+ (event.subjectType === 'enrollment'+ ? requesters.get(event.subjectId)+ : names.get(event.subjectId)) ?? null+ },+ metadata: event.metadata,+ createdAt: event.createdAt+ }))}}}diff --git a/packages/cloud/src/admin/email/service.ts b/packages/cloud/src/admin/email/service.tsindex c05371296..864cf635a 100644--- a/packages/cloud/src/admin/email/service.ts+++ b/packages/cloud/src/admin/email/service.ts@@ -61,7 +61,7 @@ export function createAdminEmailService(}const kind = original.kindconst enrollment = await transaction- .selectFrom('cloudEnrollment')+ .selectFrom('enrollment').selectAll().where('emailNormalized', '=', original.recipientEmailNormalized).executeTakeFirst()@@ -89,7 +89,7 @@ export function createAdminEmailService(transaction)await transaction- .insertInto('cloudAdminAuditEvent')+ .insertInto('adminAuditEvent').values({id: crypto.randomUUID(),actorUserId: actorId,diff --git a/packages/cloud/src/admin/enrollment/service.ts b/packages/cloud/src/admin/enrollment/service.tsindex 532481ddc..330f8be8a 100644--- a/packages/cloud/src/admin/enrollment/service.ts+++ b/packages/cloud/src/admin/enrollment/service.ts@@ -76,7 +76,7 @@ export function createEnrollmentService() {const statusForEmail = async (email: string): Promise<EnrollmentStatus | null> => {const row = await database- .selectFrom('cloudEnrollment')+ .selectFrom('enrollment').select('status').where('emailNormalized', '=', normalizeEnrollmentEmail(email)).executeTakeFirst()@@ -87,7 +87,7 @@ export function createEnrollmentService(const emailNormalized = normalizeEnrollmentEmail(input.email)await database.transaction().execute(async (transaction) => {const existing = await transaction- .selectFrom('cloudEnrollment')+ .selectFrom('enrollment').selectAll().where('emailNormalized', '=', emailNormalized).forUpdate()@@ -106,14 +106,14 @@ export function createEnrollmentService(let row: EnrollmentRowif (existing) {row = await transaction- .updateTable('cloudEnrollment')+ .updateTable('enrollment').set(values).where('id', '=', existing.id).returningAll().executeTakeFirstOrThrow()} else {row = await transaction- .insertInto('cloudEnrollment')+ .insertInto('enrollment').values({id: crypto.randomUUID(),emailNormalized,@@ -137,7 +137,7 @@ export function createEnrollmentService(return (await statusForEmail(email)) === 'approved'},async list(status?: EnrollmentStatus): Promise<EnrollmentRecord[]> {- let query = database.selectFrom('cloudEnrollment').selectAll()+ let query = database.selectFrom('enrollment').selectAll()if (status) query = query.where('status', '=', status)return (await query.orderBy('requestedAt', 'desc').execute()).map(enrollmentRecord)},@@ -149,7 +149,7 @@ export function createEnrollmentService(): Promise<EnrollmentRecord> {return database.transaction().execute(async (transaction) => {const current = await transaction- .selectFrom('cloudEnrollment')+ .selectFrom('enrollment').selectAll().where('id', '=', enrollmentId).forUpdate()@@ -170,7 +170,7 @@ export function createEnrollmentService(.executeTakeFirst(): undefinedconst row = await transaction- .updateTable('cloudEnrollment')+ .updateTable('enrollment').set({status,reviewedAt: now,@@ -183,7 +183,7 @@ export function createEnrollmentService(.returningAll().executeTakeFirstOrThrow()await transaction- .insertInto('cloudAdminAuditEvent')+ .insertInto('adminAuditEvent').values({id: crypto.randomUUID(),actorUserId: actorId,@@ -206,15 +206,43 @@ export function createEnrollmentService(},async bindApprovedUser(email: string, userId: string): Promise<void> {await database- .updateTable('cloudEnrollment')+ .updateTable('enrollment').set({ approvedUserId: userId }).where('emailNormalized', '=', normalizeEnrollmentEmail(email)).where('status', '=', 'approved').execute()},+ /**+ * Moves an approved account's enrollment to the address it changed to, so the approval stays+ * with the account rather than with an address it no longer uses. Any other request from the+ * new address gives way to it.+ */+ async followEmailChange(userId: string, email: string): Promise<void> {+ const emailNormalized = normalizeEnrollmentEmail(email)+ await database.transaction().execute(async (transaction) => {+ const approved = await transaction+ .selectFrom('enrollment')+ .select(['id', 'emailNormalized'])+ .where('approvedUserId', '=', userId)+ .where('status', '=', 'approved')+ .forUpdate()+ .executeTakeFirst()+ if (!approved || approved.emailNormalized === emailNormalized) return+ await transaction+ .deleteFrom('enrollment')+ .where('emailNormalized', '=', emailNormalized)+ .where('id', '!=', approved.id)+ .execute()+ await transaction+ .updateTable('enrollment')+ .set({ emailNormalized })+ .where('id', '=', approved.id)+ .execute()+ })+ },async pendingCount(): Promise<number> {const row = await database- .selectFrom('cloudEnrollment')+ .selectFrom('enrollment').select(({ fn }) => fn.countAll<number>().as('count')).where('status', '=', 'pending').executeTakeFirstOrThrow()diff --git a/packages/cloud/src/admin/operations/service.ts b/packages/cloud/src/admin/operations/service.tsindex c9db49cf0..a4a6d1461 100644--- a/packages/cloud/src/admin/operations/service.ts+++ b/packages/cloud/src/admin/operations/service.ts@@ -17,14 +17,39 @@ export function createAdminOperationsService(return {async summary() {- const [pendingEnrollment, pendingEmail, failedEmail] = await Promise.all([+ const [+ pendingEnrollment,+ pendingEmail,+ failedEmail,+ accounts,+ workspaces,+ documents,+ stored+ ] = await Promise.all([database- .selectFrom('cloudEnrollment')+ .selectFrom('enrollment').select(({ fn }) => fn.countAll<number>().as('count')).where('status', '=', 'pending').executeTakeFirstOrThrow(),emailCount('pending'),- emailCount('failed')+ emailCount('failed'),+ database+ .selectFrom('user')+ .select(({ fn }) => fn.countAll<number>().as('count'))+ .executeTakeFirstOrThrow(),+ database+ .selectFrom('workspace')+ .select(({ fn }) => fn.countAll<number>().as('count'))+ .executeTakeFirstOrThrow(),+ database+ .selectFrom('document')+ .select(({ fn }) => fn.countAll<number>().as('count'))+ .where('deletedAt', 'is', null)+ .executeTakeFirstOrThrow(),+ database+ .selectFrom('workspaceStorageUsage')+ .select(({ fn }) => fn.sum<number | null>('committedBytes').as('bytes'))+ .executeTakeFirstOrThrow()])return {deployment: config.deployment,@@ -32,7 +57,11 @@ export function createAdminOperationsService(emailTransport: config.emailTransport,pendingEnrollment: Number(pendingEnrollment.count),pendingEmail,- failedEmail+ failedEmail,+ accounts: Number(accounts.count),+ workspaces: Number(workspaces.count),+ documents: Number(documents.count),+ storedBytes: Number(stored.bytes ?? 0)}}}diff --git a/packages/cloud/src/admin/users/service.ts b/packages/cloud/src/admin/users/service.tsindex 70f672043..f65b0d0d2 100644--- a/packages/cloud/src/admin/users/service.ts+++ b/packages/cloud/src/admin/users/service.ts@@ -1,40 +1,115 @@import { AdminDomainError } from '#cloud/admin/errors'import { ADMIN_LIST_MAXIMUM } from '#cloud/admin/schema'-import type { CloudAuthAdapter } from '#cloud/server/auth'+import type { CloudAdminUser, CloudAdminUserDetail, CloudAdminUserFilter } from '#cloud/contract'+import {+ createSignInActivity,+ type AuthenticationEmailService,+ type CloudAuthAdapter+} from '#cloud/server/auth'import type { CloudDatabase } from '#cloud/server/db'-import { clamp } from 'es-toolkit'-import type { Kysely } from 'kysely'+import { dateString } from '#cloud/server/sharing/contracts'+import { clamp, countBy, keyBy } from 'es-toolkit'+import type { ExpressionBuilder, Kysely } from 'kysely'++/** The sign-ins a person's page lists. */+const DETAIL_SIGN_INS = 20++const FILTERS = ['all', 'administrators', 'suspended', 'without-two-step'] as const++type UserExpression = ExpressionBuilder<CloudDatabase, 'user'>++/** A search for part of a name or email, matched literally and without case. */+function searchCondition(search: string) {+ const pattern = `%${search.replace(/[\\%_]/g, (character) => `\\${character}`)}%`+ return (expression: UserExpression) =>+ expression.or([+ expression('user.email', 'ilike', pattern),+ expression('user.name', 'ilike', pattern)+ ])+}++function filterCondition(filter: CloudAdminUserFilter) {+ return (expression: UserExpression) => {+ if (filter === 'administrators') return expression('user.role', '=', 'admin')+ if (filter === 'suspended') return expression('user.banned', '=', true)+ if (filter === 'without-two-step') {+ return expression.and([+ // Better Auth leaves the flag unset on accounts that never turned it on.+ expression('user.twoFactorEnabled', 'is not', true),+ expression.not(+ expression.exists(+ expression+ .selectFrom('passkey')+ .select('passkey.id')+ .whereRef('passkey.userId', '=', 'user.id')+ )+ )+ ])+ }+ return expression.lit(true)+ }+}++export type AdminUserQuery = {+ search?: string+ filter?: CloudAdminUserFilter+ limit?: number+ offset?: number+}++type UserRow = {+ id: string+ name: string+ email: string+ image: string | null+ role: string | null+ banned: boolean | null+ banReason: string | null+ twoFactorEnabled: boolean | null+ createdAt: Date | string+}export function createAdminUserService(database: Kysely<CloudDatabase>,auth: CloudAuthAdapter,- options: { requireMFA?: boolean } = {}+ options: { requireMFA?: boolean; notify?: AuthenticationEmailService } = {}) {- async function audit(actorId: string, action: string, userId: string): Promise<void> {+ const activity = createSignInActivity(database)++ async function audit(+ actorId: string,+ action: string,+ userId: string,+ metadata: Record<string, unknown> = {}+ ): Promise<void> {await database- .insertInto('cloudAdminAuditEvent')+ .insertInto('adminAuditEvent').values({id: crypto.randomUUID(),actorUserId: actorId,action,subjectType: 'user',subjectId: userId,- metadata: {}+ metadata}).execute()}- async function requireSafeTarget(- actorId: string,- userId: string,- action: 'ban' | 'demote'- ): Promise<void> {+ function refuseSelf(actorId: string, userId: string, action: string): void {if (actorId === userId) {throw new AdminDomainError('self_admin_action_forbidden',`Administrators cannot ${action} themselves`)}+ }++ async function requireSafeTarget(+ actorId: string,+ userId: string,+ action: 'ban' | 'demote'+ ): Promise<void> {+ refuseSelf(actorId, userId, action)const target = await database.selectFrom('user').select('role')@@ -57,17 +132,157 @@ export function createAdminUserService(}}+ /** What the list shows about each account beyond its own row. */+ async function accountSummaries(rows: UserRow[]): Promise<CloudAdminUser[]> {+ const ids = rows.map((row) => row.id)+ if (ids.length === 0) return []+ const [passkeys, sessions, memberships] = await Promise.all([+ database.selectFrom('passkey').select('userId').where('userId', 'in', ids).execute(),+ database+ .selectFrom('session')+ .select(({ fn }) => ['session.userId', fn.max('session.updatedAt').as('lastActiveAt')])+ .where('session.userId', 'in', ids)+ .where('session.expiresAt', '>', new Date())+ .groupBy('session.userId')+ .execute(),+ database.selectFrom('workspaceMember').select('userId').where('userId', 'in', ids).execute()+ ])+ const withPasskeys = new Set(passkeys.map((passkey) => passkey.userId))+ const lastActive = keyBy(sessions, (session) => session.userId)+ const workspaceCounts = countBy(memberships, (membership) => membership.userId)+ return rows.map((row) => ({+ id: row.id,+ name: row.name,+ email: row.email,+ image: row.image,+ role: row.role ?? undefined,+ banned: row.banned,+ banReason: row.banReason,+ createdAt: dateString(row.createdAt) ?? '',+ twoStep: row.twoFactorEnabled === true || withPasskeys.has(row.id),+ lastActiveAt: dateString(lastActive[row.id]?.lastActiveAt ?? null),+ workspaceCount: workspaceCounts[row.id] ?? 0+ }))+ }++ const userColumns = [+ 'user.id',+ 'user.name',+ 'user.email',+ 'user.image',+ 'user.role',+ 'user.banned',+ 'user.banReason',+ 'user.twoFactorEnabled',+ 'user.emailVerified',+ 'user.createdAt'+ ] as const+return {- list(headers: Headers, query?: { searchValue?: string; limit?: number; offset?: number }) {- return auth.listUsers(headers, {- ...query,- limit: clamp(query?.limit ?? 100, 1, ADMIN_LIST_MAXIMUM)- })+ /** A page of accounts in sign-up order, with how many match the search under each filter. */+ async list(query: AdminUserQuery = {}) {+ const search = query.search?.trim()+ const filter = query.filter ?? 'all'+ const matching = (target: CloudAdminUserFilter) => {+ let selection = database.selectFrom('user').where(filterCondition(target))+ if (search) selection = selection.where(searchCondition(search))+ return selection+ }+ const counts = await Promise.all(+ FILTERS.map(async (target) => {+ const row = await matching(target)+ .select(({ fn }) => fn.countAll<number>().as('count'))+ .executeTakeFirstOrThrow()+ return Number(row.count)+ })+ )+ const [all = 0, administrators = 0, suspended = 0, withoutTwoStep = 0] = counts+ const countsByFilter = {+ all,+ administrators,+ suspended,+ 'without-two-step': withoutTwoStep+ }+ const rows = await matching(filter)+ .select(userColumns)+ .orderBy('user.createdAt')+ .orderBy('user.id')+ .limit(clamp(query.limit ?? 50, 1, ADMIN_LIST_MAXIMUM))+ .offset(Math.max(0, query.offset ?? 0))+ .execute()+ return {+ users: await accountSummaries(rows),+ total: countsByFilter[filter],+ counts: countsByFilter+ }+ },++ /** Everything an administrator reads about one account; null when there is none. */+ async detail(userId: string): Promise<CloudAdminUserDetail | null> {+ const row = await database+ .selectFrom('user')+ .select(userColumns)+ .where('user.id', '=', userId)+ .executeTakeFirst()+ if (!row) return null+ const [[summary], methods, passkeys, sessions, signIns, workspaces] = await Promise.all([+ accountSummaries([row]),+ database+ .selectFrom('account')+ .select(['providerId', 'createdAt'])+ .where('userId', '=', userId)+ .orderBy('createdAt')+ .execute(),+ database+ .selectFrom('passkey')+ .select(({ fn }) => fn.countAll<number>().as('count'))+ .where('userId', '=', userId)+ .executeTakeFirstOrThrow(),+ activity.sessions(userId, ''),+ activity.signIns(userId, DETAIL_SIGN_INS),+ database+ .selectFrom('workspaceMember')+ .innerJoin('workspace', 'workspace.id', 'workspaceMember.workspaceId')+ .select((expression) => [+ 'workspace.id',+ 'workspace.name',+ 'workspaceMember.role',+ 'workspaceMember.createdAt',+ expression+ .selectFrom('workspaceMember as member')+ .select(({ fn }) => fn.countAll<number>().as('count'))+ .whereRef('member.workspaceId', '=', 'workspace.id')+ .as('memberCount')+ ])+ .where('workspaceMember.userId', '=', userId)+ .orderBy('workspaceMember.createdAt')+ .execute()+ ])+ if (!summary) return null+ return {+ user: { ...summary, emailVerified: row.emailVerified },+ methods: methods.map((method) => ({+ provider: method.providerId,+ createdAt: dateString(method.createdAt) ?? ''+ })),+ authenticator: row.twoFactorEnabled === true,+ passkeyCount: Number(passkeys.count),+ sessions,+ signIns,+ workspaces: workspaces.map((workspace) => ({+ id: workspace.id,+ name: workspace.name,+ role: workspace.role,+ memberCount: Number(workspace.memberCount ?? 0),+ joinedAt: dateString(workspace.createdAt) ?? ''+ }))+ }},+async ban(headers: Headers, actorId: string, userId: string, reason?: string): Promise<void> {await requireSafeTarget(actorId, userId, 'ban')await auth.banUser(headers, userId, reason)- await audit(actorId, 'user.banned', userId)+ await audit(actorId, 'user.banned', userId, reason ? { reason } : {})},async unban(headers: Headers, actorId: string, userId: string): Promise<void> {await auth.unbanUser(headers, userId)@@ -104,6 +319,48 @@ export function createAdminUserService(}await auth.setRole(headers, userId, enabled ? 'admin' : 'user')await audit(actorId, enabled ? 'user.admin-granted' : 'user.admin-revoked', userId)+ },++ /**+ * Removes an account's authenticator app, recovery codes, and passkeys, for someone who lost+ * them; they sign in with their password or a linked account and set them up again.+ */+ async resetTwoStep(actorId: string, userId: string): Promise<void> {+ refuseSelf(actorId, userId, 'reset two-step sign-in for')+ const user = await database.transaction().execute(async (transaction) => {+ const target = await transaction+ .selectFrom('user')+ .select(['id', 'email', 'name'])+ .where('id', '=', userId)+ .forUpdate()+ .executeTakeFirstOrThrow()+ await transaction.deleteFrom('twoFactor').where('userId', '=', userId).execute()+ await transaction.deleteFrom('passkey').where('userId', '=', userId).execute()+ await transaction.deleteFrom('mfaAssurance').where('userId', '=', userId).execute()+ await transaction+ .updateTable('user')+ .set({ twoFactorEnabled: false, updatedAt: new Date() })+ .where('id', '=', userId)+ .execute()+ await transaction+ .insertInto('adminAuditEvent')+ .values({+ id: crypto.randomUUID(),+ actorUserId: actorId,+ action: 'user.two-step-reset',+ subjectType: 'user',+ subjectId: userId,+ metadata: {}+ })+ .execute()+ return target+ })+ await options.notify?.sendTwoStepChanged({+ email: user.email,+ name: user.name,+ userId: user.id,+ change: 'reset-by-administrator'+ })}}}diff --git a/packages/cloud/src/client/portal/account.ts b/packages/cloud/src/client/portal/account.tsindex 5465f3dc9..4452d374c 100644--- a/packages/cloud/src/client/portal/account.ts+++ b/packages/cloud/src/client/portal/account.ts@@ -1,5 +1,6 @@import {cloudAccountMutationResponseSchema,+ cloudAccountSessionsResponseSchema,cloudAccountStatusResponseSchema,cloudAuthenticationMethodsResponseSchema,cloudMFAEnableResponseSchema,@@ -7,6 +8,8 @@ import {cloudMFAStatusResponseSchema,cloudMFAVerifyResponseSchema,cloudPasskeysResponseSchema,+ cloudProfileResponseSchema,+ cloudSignInsResponseSchema,cloudSocialLinkResponseSchema} from '#cloud/contract'@@ -103,6 +106,56 @@ export function createAccountAPI(call: CloudCall, { account }: PortalRouteClientsignal)},+ profile(signal?: AbortSignal) {+ return call(+ (options) => account.profile.$get(undefined, options),+ cloudProfileResponseSchema,+ signal+ )+ },+ updateProfile(name: string, signal?: AbortSignal) {+ return call(+ (options) => account.profile.$post({ json: { name } }, 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(+ (options) => account.profile.email.$post({ json: { newEmail, callbackURL } }, options),+ cloudAccountMutationResponseSchema,+ signal+ )+ },+ sessions(signal?: AbortSignal) {+ return call(+ (options) => account.sessions.$get(undefined, options),+ cloudAccountSessionsResponseSchema,+ signal+ )+ },+ revokeSession(sessionId: string, signal?: AbortSignal) {+ return call(+ (options) => account.sessions.revoke.$post({ json: { sessionId } }, options),+ cloudAccountMutationResponseSchema,+ signal+ )+ },+ revokeOtherSessions(signal?: AbortSignal) {+ return call(+ (options) => account.sessions['revoke-others'].$post(undefined, options),+ cloudAccountMutationResponseSchema,+ signal+ )+ },+ signIns(signal?: AbortSignal) {+ return call(+ (options) => account['sign-ins'].$get(undefined, options),+ cloudSignInsResponseSchema,+ signal+ )+ },unlinkAuthenticationMethod(methodId: string, signal?: AbortSignal) {return call((options) => account.authentication.unlink.$post({ json: { methodId } }, options),diff --git a/packages/cloud/src/client/portal/administration.ts b/packages/cloud/src/client/portal/administration.tsindex 510e7d008..4b4081295 100644--- a/packages/cloud/src/client/portal/administration.ts+++ b/packages/cloud/src/client/portal/administration.ts@@ -4,9 +4,11 @@ import {adminMutationResponseSchema,adminOperationsResponseSchema,cloudAdminSessionResponseSchema,+ cloudAdminUserDetailSchema,cloudAdminUsersResponseSchema,enrollmentReviewResponseSchema,enrollmentsResponseSchema,+ type CloudAdminUserFilter,type enrollmentStatusSchema} from '#cloud/contract'import type * as v from 'valibot'@@ -44,15 +46,36 @@ export function createAdministrationAPI(call: CloudCall, { admin, api }: PortalRsignal)},- users(search?: string, signal?: AbortSignal) {+ users(+ query: { search?: string; filter?: CloudAdminUserFilter; limit?: number; offset?: number },+ signal?: AbortSignal+ ) {return call(- (options) => admin.users.$get({ query: { search: search || undefined } }, options),+ (options) =>+ admin.users.$get(+ {+ query: {+ search: query.search || undefined,+ filter: query.filter,+ limit: query.limit,+ offset: query.offset+ }+ },+ options+ ),cloudAdminUsersResponseSchema,signal)},+ user(id: string, signal?: AbortSignal) {+ return call(+ (options) => admin.users[':id'].$get({ param: { id } }, options),+ cloudAdminUserDetailSchema,+ signal+ )+ },userAction(- action: 'ban' | 'unban' | 'revoke-sessions',+ action: 'ban' | 'unban' | 'revoke-sessions' | 'reset-two-step',userId: string,reason?: string,signal?: AbortSignaldiff --git a/packages/cloud/src/client/portal/request.ts b/packages/cloud/src/client/portal/request.tsindex b6101ea52..bd8653ff8 100644--- a/packages/cloud/src/client/portal/request.ts+++ b/packages/cloud/src/client/portal/request.ts@@ -69,11 +69,11 @@ export function createCloudCall(options: CloudPortalClientOptions = {}): CloudCathrow new CloudPortalAPIError('network', undefined, { cause })}if (response.status === 401) throw new CloudPortalAPIError('authentication-required')- if (response.status === 403) throw new CloudPortalAPIError('authorization-required')let body: unknowntry {body = await response.json()} catch (cause) {+ if (response.status === 403) throw new CloudPortalAPIError('authorization-required')throw new CloudPortalAPIError('protocol', undefined, { cause })}if (!response.ok) {@@ -82,6 +82,11 @@ export function createCloudCall(options: CloudPortalClientOptions = {}): CloudCalet code: AdminErrorCode | AccountSecurityErrorCode | undefinedif (accountError.success) code = accountError.output.error.codeelse if (adminError.success) code = adminError.output.error.code+ // A refusal that says why, such as a session that must sign in again, is the domain's;+ // a bare or plain `forbidden` one is a missing permission.+ if (response.status === 403 && (!code || code === 'forbidden')) {+ throw new CloudPortalAPIError('authorization-required')+ }throw new CloudPortalAPIError('domain', code)}const parsed = v.safeParse(schema, body)diff --git a/packages/cloud/src/client/workspaces.ts b/packages/cloud/src/client/workspaces.tsindex c4342c41a..36600a0a9 100644--- a/packages/cloud/src/client/workspaces.ts+++ b/packages/cloud/src/client/workspaces.ts@@ -77,6 +77,19 @@ export function createWorkspaceRequests(onDiagnostic)},+ /** Sends a waiting invitation again; its earlier link stops working. */+ async resendWorkspaceInvitation(+ workspaceId: string,+ invitationId: string+ ): Promise<CreatedWorkspaceInvitation> {+ return parseResponse(+ client.workspaces[':workspaceId'].invitations[':invitationId'].resend.$post({+ param: { workspaceId, invitationId }+ }),+ createdWorkspaceInvitationSchema,+ onDiagnostic+ )+ },async revokeWorkspaceInvitation(workspaceId: string, invitationId: string): Promise<void> {await responseBody(await client.workspaces[':workspaceId'].invitations[':invitationId'].$delete({diff --git a/packages/cloud/src/contract/account.ts b/packages/cloud/src/contract/account.tsindex fb173bd82..03ea55f86 100644--- a/packages/cloud/src/contract/account.ts+++ b/packages/cloud/src/contract/account.ts@@ -5,6 +5,8 @@ export const cloudIdentitySchema = v.object({userId: v.string(),email: v.pipe(v.string(), v.email()),name: v.string(),+ /** The account's picture, such as one a social provider gave it. */+ image: v.optional(v.nullable(v.string())),deploymentRole: v.optional(v.picklist(['user', 'admin']))})@@ -40,7 +42,10 @@ export const accountSecurityErrorCodeSchema = v.picklist(['password_too_long','last_authentication_method','session_not_fresh',- 'authentication_method_failed'+ 'authentication_method_failed',+ 'email_unchanged',+ 'email_change_unavailable',+ 'current_session'])export const accountSecurityErrorResponseSchema = v.object({error: v.object({ code: accountSecurityErrorCodeSchema })@@ -93,6 +98,74 @@ 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({+ id: v.string(),+ name: v.string(),+ email: v.pipe(v.string(), v.email()),+ image: v.nullable(v.string()),+ createdAt: v.string(),+ /** Whether the server can send the verification a new email address needs. */+ emailChangeAvailable: v.boolean()+})+export const cloudProfileResponseSchema = v.object({ profile: cloudProfileSchema })+export const cloudProfileUpdateSchema = v.object({+ name: v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(100))+})+export const cloudEmailChangeSchema = v.object({+ newEmail: v.pipe(v.string(), v.trim(), v.toLowerCase(), v.email()),+ callbackURL: v.pipe(v.string(), v.url())+})++/** How a sign-in was made: the method it used, or the desktop app's approved code. */+export const cloudSignInMethodSchema = v.picklist([+ 'password',+ 'google',+ 'apple',+ 'passkey',+ 'two-step',+ 'email-link',+ 'desktop',+ 'other'+])+export const cloudAccountSessionSchema = v.object({+ id: v.string(),+ /** The session this request was made with. */+ current: v.boolean(),+ method: v.nullable(cloudSignInMethodSchema),+ ipAddress: v.nullable(v.string()),+ /** The browser and system the server read from the client's user agent, such as `Chrome 141`. */+ browser: v.nullable(v.string()),+ system: v.nullable(v.string()),+ createdAt: v.string(),+ lastActiveAt: v.string(),+ expiresAt: v.string()+})+export const cloudAccountSessionsResponseSchema = v.object({+ sessions: v.array(cloudAccountSessionSchema)+})+export const cloudSessionRevokeSchema = v.object({ sessionId: v.pipe(v.string(), v.minLength(1)) })+export const cloudSignInSchema = v.object({+ id: v.string(),+ method: cloudSignInMethodSchema,+ ipAddress: v.nullable(v.string()),+ /** The browser and system the server read from the client's user agent, such as `Chrome 141`. */+ browser: v.nullable(v.string()),+ system: v.nullable(v.string()),+ createdAt: v.string()+})+export const cloudSignInsResponseSchema = v.object({ signIns: v.array(cloudSignInSchema) })++export function parseCloudProfileUpdate(input: unknown) {+ return v.parse(cloudProfileUpdateSchema, input)+}+export function parseCloudEmailChange(input: unknown) {+ return v.parse(cloudEmailChangeSchema, input)+}+export function parseCloudSessionRevoke(input: unknown) {+ return v.parse(cloudSessionRevokeSchema, input)+}+export type AccountSecurityErrorCode = v.InferOutput<typeof accountSecurityErrorCodeSchema>export type CloudAuthenticationProvider = v.InferOutput<typeof cloudAuthenticationProviderSchema>export type CloudAuthenticationMethod = v.InferOutput<typeof cloudAuthenticationMethodSchema>@@ -101,3 +174,7 @@ export type CloudAuthenticationMethods = v.InferOutput<>export type CloudAccountStatus = v.InferOutput<typeof cloudAccountStatusResponseSchema>+export type CloudProfile = v.InferOutput<typeof cloudProfileSchema>+export type CloudSignInMethod = v.InferOutput<typeof cloudSignInMethodSchema>+export type CloudAccountSession = v.InferOutput<typeof cloudAccountSessionSchema>+export type CloudSignIn = v.InferOutput<typeof cloudSignInSchema>diff --git a/packages/cloud/src/contract/admin/index.ts b/packages/cloud/src/contract/admin/index.tsindex 11d200674..7ef2a39b7 100644--- a/packages/cloud/src/contract/admin/index.ts+++ b/packages/cloud/src/contract/admin/index.ts@@ -1,6 +1,7 @@import * as v from 'valibot'-import { cloudIdentitySchema } from '../account'+import { cloudIdentitySchema, cloudAccountSessionSchema, cloudSignInSchema } from '../account'+import { workspaceRoleSchema } from '../workspaces'const timestampSchema = v.pipe(v.string(), v.isoTimestamp())const nullableTimestampSchema = v.nullable(timestampSchema)@@ -42,18 +43,63 @@ export const enrollmentReviewResponseSchema = v.object({ enrollment: enrollmentSexport const cloudAdminSessionResponseSchema = v.object({ user: cloudIdentitySchema })+const 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()),role: v.optional(v.string()),banned: v.nullable(v.boolean()),banReason: v.optional(v.nullable(v.string())),- createdAt: timestampSchema+ createdAt: timestampSchema,+ /** An authenticator app or a passkey confirms this account's sign-ins. */+ twoStep: v.boolean(),+ /** When one of the account's sessions was last used, or null when none is left. */+ lastActiveAt: nullableTimestampSchema,+ workspaceCount: countSchema})++/** Which accounts a list of people shows. */+export const cloudAdminUserFilterSchema = v.picklist([+ 'all',+ 'administrators',+ 'suspended',+ 'without-two-step'+])export const cloudAdminUsersResponseSchema = v.object({users: v.array(cloudAdminUserSchema),- total: v.pipe(v.number(), v.integer(), v.minValue(0))+ /** How many accounts match the search and filter, across every page. */+ total: countSchema,+ /** How many accounts match the search under each filter. */+ counts: v.object({+ all: countSchema,+ administrators: countSchema,+ suspended: countSchema,+ 'without-two-step': countSchema+ })+})++export const cloudAdminUserDetailSchema = v.object({+ user: v.object({+ ...cloudAdminUserSchema.entries,+ emailVerified: v.boolean()+ }),+ methods: v.array(v.object({ provider: v.string(), createdAt: timestampSchema })),+ authenticator: v.boolean(),+ passkeyCount: countSchema,+ sessions: v.array(cloudAccountSessionSchema),+ signIns: v.array(cloudSignInSchema),+ workspaces: v.array(+ v.object({+ id: v.string(),+ name: v.string(),+ role: workspaceRoleSchema,+ memberCount: countSchema,+ joinedAt: timestampSchema+ })+ )})export const adminMutationResponseSchema = v.object({ ok: v.literal(true) })@@ -76,12 +122,15 @@ export const adminEmailResponseSchema = v.object({messages: v.array(transactionalEmailAdminSchema)})+/** Who or what an event names; `name` is null once the server no longer knows it. */+const auditPartySchema = v.object({ id: v.string(), name: v.nullable(v.string()) })+export const adminAuditEventSchema = v.object({id: v.string(),- actorUserId: v.string(),+ actor: auditPartySchema,action: v.string(),- subjectType: v.string(),- subjectId: v.string(),+ /** What the event is about: an account, an access request, or an email. */+ subject: v.object({ ...auditPartySchema.entries, type: v.string() }),metadata: v.unknown(),createdAt: timestampSchema})@@ -93,13 +142,20 @@ export const adminOperationsResponseSchema = v.object({emailTransport: v.picklist(['none', 'smtp', 'cloudflare']),pendingEnrollment: v.pipe(v.number(), v.integer(), v.minValue(0)),pendingEmail: v.pipe(v.number(), v.integer(), v.minValue(0)),- failedEmail: v.pipe(v.number(), v.integer(), v.minValue(0))+ failedEmail: v.pipe(v.number(), v.integer(), v.minValue(0)),+ accounts: countSchema,+ workspaces: countSchema,+ documents: countSchema,+ storedBytes: countSchema})export type AdminErrorCode = v.InferOutput<typeof adminErrorCodeSchema>export type Enrollment = v.InferOutput<typeof enrollmentSchema>export type CloudAdminSessionResponse = v.InferOutput<typeof cloudAdminSessionResponseSchema>export type CloudAdminUser = v.InferOutput<typeof cloudAdminUserSchema>+export type CloudAdminUserFilter = v.InferOutput<typeof cloudAdminUserFilterSchema>+export type CloudAdminUsers = v.InferOutput<typeof cloudAdminUsersResponseSchema>+export type CloudAdminUserDetail = v.InferOutput<typeof cloudAdminUserDetailSchema>export type TransactionalEmailAdmin = v.InferOutput<typeof transactionalEmailAdminSchema>export type AdminAuditEvent = v.InferOutput<typeof adminAuditEventSchema>export type AdminOperations = v.InferOutput<typeof adminOperationsResponseSchema>diff --git a/packages/cloud/src/contract/workspaces.ts b/packages/cloud/src/contract/workspaces.tsindex 4f4905f87..249094c50 100644--- a/packages/cloud/src/contract/workspaces.ts+++ b/packages/cloud/src/contract/workspaces.ts@@ -42,6 +42,7 @@ export const workspaceMemberSchema = v.object({userId: v.string(),name: v.string(),email: v.string(),+ image: v.nullable(v.string()),role: workspaceRoleSchema,joinedAt: v.string()})@@ -52,6 +53,8 @@ export const workspaceInvitationSchema = v.object({id: v.pipe(v.string(), v.uuid()),email: v.string(),role: workspaceRoleSchema,+ /** Who sent it; the name is null once their account is gone. */+ invitedBy: v.object({ id: v.string(), name: v.nullable(v.string()) }),invitedAt: v.string(),expiresAt: v.string()})diff --git a/packages/cloud/src/email/index.ts b/packages/cloud/src/email/index.tsindex d71487f55..ab55d5ffd 100644--- a/packages/cloud/src/email/index.ts+++ b/packages/cloud/src/email/index.ts@@ -8,5 +8,6 @@ export type {TransactionalEmailContent,TransactionalEmailKind,TransactionalEmailMessage,- TransactionalEmailPayloadByKind+ TransactionalEmailPayloadByKind,+ TwoStepChange} from './schema'diff --git a/packages/cloud/src/email/render.ts b/packages/cloud/src/email/render.tsindex 5341656a4..90f639bf4 100644--- a/packages/cloud/src/email/render.ts+++ b/packages/cloud/src/email/render.ts@@ -1,14 +1,19 @@import { render } from '@vue-email/render'+import { compact } from 'es-toolkit'import type {AdminEnrollmentNotificationPayload,AuthenticationEmailPayload,DocumentInvitationEmailPayload,- WorkspaceInvitationEmailPayload,+ EmailChangeRequestedPayload,EnrollmentEmailPayload,+ NewSignInPayload,RenderedTransactionalEmail,TransactionalEmailContent,- TransactionalEmailKind+ TransactionalEmailKind,+ TwoStepChange,+ TwoStepChangedPayload,+ WorkspaceInvitationEmailPayload} from './schema'import { DocumentInvitationEmail } from './templates/document-invitation'import { EnrollmentEmail } from './templates/enrollment'@@ -66,6 +71,9 @@ type EnrollmentMessageKind = Exclude<| 'email-verification'| 'password-reset'| 'password-changed'+ | 'email-change-requested'+ | 'new-sign-in'+ | 'two-step-changed'>type EnrollmentCopy = {@@ -138,14 +146,24 @@ async function renderAuthentication(payload: AuthenticationEmailPayload) {const copy = {- 'email-verification': {- subject: 'Confirm your OpenPencil Cloud email',- heading: 'Confirm your email',- preview: 'One click to finish creating your OpenPencil Cloud account.',- message: `Hi ${payload.name}, confirm this address to finish creating your OpenPencil Cloud account. Then go back to OpenPencil; it signs you in by itself.`,- actionLabel: 'Confirm email',- footer: 'Didn’t create an account? Ignore this email and nothing happens.'- },+ 'email-verification':+ payload.purpose === 'change'+ ? {+ subject: 'Confirm your new OpenPencil Cloud email',+ heading: 'Confirm your new email',+ preview: 'One click to move your OpenPencil Cloud account to this address.',+ message: `Hi ${payload.name}, confirm this address to make it your OpenPencil Cloud account’s email. Your old address stays until you do.`,+ actionLabel: 'Confirm email',+ footer: 'Didn’t ask for this? Ignore this email and nothing changes.'+ }+ : {+ subject: 'Confirm your OpenPencil Cloud email',+ heading: 'Confirm your email',+ preview: 'One click to finish creating your OpenPencil Cloud account.',+ message: `Hi ${payload.name}, confirm this address to finish creating your OpenPencil Cloud account. Then go back to OpenPencil; it signs you in by itself.`,+ actionLabel: 'Confirm email',+ footer: 'Didn’t create an account? Ignore this email and nothing happens.'+ },'password-reset': {subject: 'Reset your OpenPencil Cloud password',heading: 'Reset your password',@@ -165,6 +183,77 @@ async function renderAuthentication(return rendered(EnrollmentEmail, { ...copy, actionURL: payload.actionURL ?? '#' }, copy.subject)}+async function renderEmailChangeRequested(payload: EmailChangeRequestedPayload) {+ return rendered(+ EnrollmentEmail,+ {+ heading: 'Your email is changing',+ preview: `Your OpenPencil Cloud email is changing to ${payload.newEmail}.`,+ message: `Hi ${payload.name}, someone signed in to your account asked to change its email to ${payload.newEmail}. It changes once that address confirms it. If this wasn’t you, change your password and sign out of your other sessions.`,+ actionLabel: 'Review your account',+ actionURL: payload.actionURL+ },+ 'Your OpenPencil Cloud email is changing'+ )+}++async function renderNewSignIn(payload: NewSignInPayload) {+ const device = payload.desktop+ ? 'the OpenPencil app'+ : compact([payload.browser, payload.system]).join(' on ') || 'an unknown browser'+ const place = payload.ipAddress ? ` from ${payload.ipAddress}` : ''+ return rendered(+ EnrollmentEmail,+ {+ heading: 'New sign-in to your account',+ preview: `Your OpenPencil Cloud account was signed in to with ${device}.`,+ message: `Hi ${payload.name}, your account was signed in to with ${device}${place} on ${new Date(payload.signedInAt).toUTCString()}. If this was you, there’s nothing to do. If it wasn’t, sign that session out and change your password.`,+ actionLabel: 'Review sessions',+ actionURL: payload.actionURL+ },+ 'New sign-in to your OpenPencil Cloud account'+ )+}++const TWO_STEP_COPY: Record<TwoStepChange, { heading: string; message: string }> = {+ 'authenticator-on': {+ heading: 'Authenticator app turned on',+ message: 'an authenticator app now confirms your sign-ins.'+ },+ 'authenticator-off': {+ heading: 'Authenticator app turned off',+ message: 'your sign-ins no longer ask for a code from an authenticator app.'+ },+ 'passkey-added': {+ heading: 'Passkey added',+ message: 'a passkey was added to your account.'+ },+ 'passkey-removed': {+ heading: 'Passkey removed',+ message: 'a passkey was removed from your account.'+ },+ 'reset-by-administrator': {+ heading: 'Two-step sign-in was reset',+ message:+ 'an administrator removed your authenticator app, recovery codes, and passkeys, so you can set them up again.'+ }+}++async function renderTwoStepChanged(payload: TwoStepChangedPayload) {+ const copy = TWO_STEP_COPY[payload.change]+ return rendered(+ EnrollmentEmail,+ {+ heading: copy.heading,+ preview: `${copy.heading} on your OpenPencil Cloud account.`,+ message: `Hi ${payload.name}, ${copy.message} If this wasn’t you, change your password and contact your administrator.`,+ actionLabel: 'Review security',+ actionURL: payload.actionURL+ },+ `${copy.heading} on your OpenPencil Cloud account`+ )+}+export async function renderTransactionalEmail(content: TransactionalEmailContent): Promise<RenderedTransactionalEmail> {@@ -180,5 +269,8 @@ export async function renderTransactionalEmail() {return renderAuthentication(content.kind, content.payload)}+ if (content.kind === 'email-change-requested') return renderEmailChangeRequested(content.payload)+ if (content.kind === 'new-sign-in') return renderNewSignIn(content.payload)+ if (content.kind === 'two-step-changed') return renderTwoStepChanged(content.payload)return renderEnrollment(content.kind, content.payload)}diff --git a/packages/cloud/src/email/schema.ts b/packages/cloud/src/email/schema.tsindex a6fc23871..1f2bea2d5 100644--- a/packages/cloud/src/email/schema.ts+++ b/packages/cloud/src/email/schema.ts@@ -12,6 +12,9 @@ export type TransactionalEmailKind =| 'email-verification'| 'password-reset'| 'password-changed'+ | 'email-change-requested'+ | 'new-sign-in'+ | 'two-step-changed'const documentInvitationEmailPayloadSchema = v.object({inviterName: v.string(),@@ -43,7 +46,40 @@ const adminEnrollmentNotificationPayloadSchema = v.object({const authenticationEmailPayloadSchema = v.object({name: v.string(),- actionURL: v.optional(v.string())+ actionURL: v.optional(v.string()),+ /** What a verification link confirms: a new account, or a new address for one. */+ purpose: v.optional(v.picklist(['account', 'change']))+})++const emailChangeRequestedPayloadSchema = v.object({+ name: v.string(),+ newEmail: v.string(),+ actionURL: v.string()+})++const newSignInPayloadSchema = v.object({+ name: v.string(),+ signedInAt: v.string(),+ ipAddress: v.nullable(v.string()),+ browser: v.nullable(v.string()),+ system: v.nullable(v.string()),+ desktop: v.boolean(),+ actionURL: v.string()+})++/** What changed about how an account proves it is its owner's. */+export const twoStepChangeSchema = v.picklist([+ 'authenticator-on',+ 'authenticator-off',+ 'passkey-added',+ 'passkey-removed',+ 'reset-by-administrator'+])++const twoStepChangedPayloadSchema = v.object({+ name: v.string(),+ change: twoStepChangeSchema,+ actionURL: v.string()})function content<const Kind extends TransactionalEmailKind, Payload extends v.GenericSchema>(@@ -63,7 +99,10 @@ export const transactionalEmailContentSchema = v.variant('kind', [content('enrollment-revoked', enrollmentEmailPayloadSchema),content('email-verification', authenticationEmailPayloadSchema),content('password-reset', authenticationEmailPayloadSchema),- content('password-changed', authenticationEmailPayloadSchema)+ content('password-changed', authenticationEmailPayloadSchema),+ content('email-change-requested', emailChangeRequestedPayloadSchema),+ content('new-sign-in', newSignInPayloadSchema),+ content('two-step-changed', twoStepChangedPayloadSchema)])/** A transactional email's kind with the payload that kind renders. */@@ -80,6 +119,10 @@ export type AdminEnrollmentNotificationPayload = v.InferOutput<typeof adminEnrollmentNotificationPayloadSchema>export type AuthenticationEmailPayload = v.InferOutput<typeof authenticationEmailPayloadSchema>+export type EmailChangeRequestedPayload = v.InferOutput<typeof emailChangeRequestedPayloadSchema>+export type NewSignInPayload = v.InferOutput<typeof newSignInPayloadSchema>+export type TwoStepChange = v.InferOutput<typeof twoStepChangeSchema>+export type TwoStepChangedPayload = v.InferOutput<typeof twoStepChangedPayloadSchema>export type TransactionalEmailPayloadByKind = {[Kind in TransactionalEmailKind]: Extract<TransactionalEmailContent, { kind: Kind }>['payload']diff --git a/packages/cloud/src/runtime/node/admin.ts b/packages/cloud/src/runtime/node/admin.tsindex 1de845146..9052cafcc 100644--- a/packages/cloud/src/runtime/node/admin.ts+++ b/packages/cloud/src/runtime/node/admin.ts@@ -12,7 +12,7 @@ try {const normalized = email.trim().toLowerCase()if (operation === 'approve') {await database- .insertInto('cloudEnrollment')+ .insertInto('enrollment').values({id: crypto.randomUUID(),emailNormalized: normalized,@@ -42,7 +42,7 @@ try {.executeTakeFirstOrThrow()await database.updateTable('user').set({ role: 'admin' }).where('id', '=', user.id).execute()await database- .insertInto('cloudAdminAuditEvent')+ .insertInto('adminAuditEvent').values({id: crypto.randomUUID(),actorUserId: 'cli-bootstrap',diff --git a/packages/cloud/src/server/account/actions.ts b/packages/cloud/src/server/account/actions.tsindex 20719d084..0fe940d0c 100644--- a/packages/cloud/src/server/account/actions.ts+++ b/packages/cloud/src/server/account/actions.ts@@ -8,7 +8,10 @@ const ACCOUNT_SECURITY_ERROR_CODES: Record<string, AccountSecurityErrorCode> = {PASSWORD_TOO_SHORT: 'password_too_short',PASSWORD_TOO_LONG: 'password_too_long',FAILED_TO_UNLINK_LAST_ACCOUNT: 'last_authentication_method',- SESSION_NOT_FRESH: 'session_not_fresh'+ SESSION_NOT_FRESH: 'session_not_fresh',+ CHANGE_EMAIL_DISABLED: 'email_change_unavailable',+ CURRENT_SESSION: 'current_session',+ EMAIL_UNCHANGED: 'email_unchanged'}async function accountAction<Value>(operation: () => Promise<Value>, context: Context) {diff --git a/packages/cloud/src/server/account/routes.ts b/packages/cloud/src/server/account/routes.tsindex d730d96b0..20ae5df2c 100644--- a/packages/cloud/src/server/account/routes.ts+++ b/packages/cloud/src/server/account/routes.ts@@ -5,7 +5,10 @@ import {parseCloudMFAVerify,parseCloudPasskeyDelete,parseCloudSocialLink,- parseCloudUnlinkAuthenticationMethod+ parseCloudUnlinkAuthenticationMethod,+ parseCloudEmailChange,+ parseCloudProfileUpdate,+ parseCloudSessionRevoke} from '#cloud/contract'import type { CloudAPIEnvironment } from '#cloud/server/api'import {@@ -188,6 +191,71 @@ export function createAccountRoutes(services: AccountRouteDependencies) {return result instanceof Response ? result : context.json({ ok: true as const })})+ .use('/api/account/profile', requireActiveSession)+ .use('/api/account/profile/*', requireActiveSession)+ .use('/api/account/sessions', requireActiveSession)+ .use('/api/account/sessions/*', requireActiveSession)+ .use('/api/account/sign-ins', requireActiveSession)+ .use('/api/account/profile', authenticatedMutationLimiter)+ .use('/api/account/profile/*', authenticatedMutationLimiter)+ .use('/api/account/sessions/*', authenticatedMutationLimiter)+ .get('/api/account/profile', async (context) => {+ const profile = await services.auth.profile(context.req.raw.headers)+ if (!profile) return context.json({ error: { code: 'unauthorized' as const } }, 401)+ return context.json({+ profile: {+ ...profile,+ createdAt: profile.createdAt.toISOString(),+ emailChangeAvailable: services.auth.emailChangeAvailable+ }+ })+ })+ .post('/api/account/profile', validatedJSON(parseCloudProfileUpdate), async (context) => {+ const result = await accountAction(+ () => services.auth.updateProfile(context.req.raw.headers, context.req.valid('json')),+ context+ )+ return result instanceof Response ? result : 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')),+ context+ )+ return result instanceof Response ? result : context.json({ ok: true as const })+ })+ .get('/api/account/sessions', async (context) => {+ const sessions = await services.auth.sessions(context.req.raw.headers)+ if (!sessions) return context.json({ error: { code: 'unauthorized' as const } }, 401)+ return context.json({ sessions })+ })+ .post(+ '/api/account/sessions/revoke',+ validatedJSON(parseCloudSessionRevoke),+ async (context) => {+ const result = await accountAction(+ () =>+ services.auth.revokeSession(+ context.req.raw.headers,+ context.req.valid('json').sessionId+ ),+ context+ )+ return result instanceof Response ? result : context.json({ ok: true as const })+ }+ )+ .post('/api/account/sessions/revoke-others', async (context) => {+ const result = await accountAction(+ () => services.auth.revokeOtherSessions(context.req.raw.headers),+ context+ )+ return result instanceof Response ? result : context.json({ ok: true as const })+ })+ .get('/api/account/sign-ins', async (context) => {+ const signIns = await services.auth.signIns(context.req.raw.headers)+ if (!signIns) return context.json({ error: { code: 'unauthorized' as const } }, 401)+ return context.json({ signIns })+ }).get('/api/account/authentication', async (context) => {const result = await accountAction(() => accountAuthentication.methods(context.req.raw.headers),diff --git a/packages/cloud/src/server/app.ts b/packages/cloud/src/server/app.tsindex af2d765dc..eb3b7e344 100644--- a/packages/cloud/src/server/app.ts+++ b/packages/cloud/src/server/app.ts@@ -21,6 +21,7 @@ import {type CloudAPIEnvironment} from '#cloud/server/api'import {+ createAuthenticationEmailService,createCloudIdentityResolver,createCloudSessionResolver,type CloudAuthAdapter,@@ -186,7 +187,10 @@ export function createCloudApp(services: CloudServices) {}),enrollment,users: createAdminUserService(services.database, services.auth, {- requireMFA: services.config.deploymentAdminMFARequired+ requireMFA: services.config.deploymentAdminMFARequired,+ notify: services.transactionalEmail+ ? createAuthenticationEmailService(services.transactionalEmail, services.config.publicURL)+ : undefined}),audit: createAdminAuditService(services.database),operations: createAdminOperationsService(services.database, services.config)diff --git a/packages/cloud/src/server/auth/account.ts b/packages/cloud/src/server/auth/account.tsindex 8fffd7843..41b8f4f45 100644--- a/packages/cloud/src/server/auth/account.ts+++ b/packages/cloud/src/server/auth/account.ts@@ -55,6 +55,17 @@ export function createAccountAuthenticationService(},async unlink(headers: Headers, methodId: string): Promise<void> {await auth.unlinkAuthenticationMethod(headers, methodId)+ },+ /** Asks for a new address; the link that confirms it comes back to this server's pages. */+ async changeEmail(+ headers: Headers,+ input: { newEmail: string; callbackURL: string }+ ): Promise<void> {+ const callback = new URL(input.callbackURL)+ if (callback.origin !== new URL(config.publicURL).origin) {+ throw new Error('Email change callback origin is unavailable')+ }+ await auth.changeEmail(headers, { ...input, callbackURL: callback.href })}}}diff --git a/packages/cloud/src/server/auth/activity.ts b/packages/cloud/src/server/auth/activity.tsnew file mode 100644index 000000000..c59873665--- /dev/null+++ b/packages/cloud/src/server/auth/activity.ts@@ -0,0 +1,196 @@+import type { CloudAccountSession, CloudSignIn, CloudSignInMethod } from '#cloud/contract'+import type { CloudDatabase } from '#cloud/server/db'+import { dateString } from '#cloud/server/sharing/contracts'+import type { BetterAuthPlugin } from 'better-auth'+import { createAuthMiddleware, isAPIError } from 'better-auth/api'+import type { Kysely } from 'kysely'++import type { AuthenticationEmailService } from './email'+import { describeUserAgent } from './user-agent'++/** The newest sign-ins an account's history shows. */+const SIGN_IN_HISTORY_LIMIT = 50++/** The Better Auth endpoints that sign someone in, and the method each one is. */+const ENDPOINT_METHODS: Record<string, CloudSignInMethod> = {+ '/sign-in/email': 'password',+ '/passkey/verify-authentication': 'passkey',+ '/two-factor/verify-totp': 'two-step',+ '/two-factor/verify-backup-code': 'two-step',+ '/verify-email': 'email-link',+ '/device/token': 'desktop'+}++/**+ * How an endpoint signed someone in, or null when it signs nobody in, such as one that refreshes+ * a session. A provider's callback names the provider, as Better Auth's own `lastLoginMethod`+ * reads it.+ */+export function signInMethod(endpoint: {+ path?: string+ params?: Record<string, string | undefined>+}): CloudSignInMethod | null {+ const path = endpoint.path ?? ''+ if (path.startsWith('/callback/')) {+ const provider = endpoint.params?.id+ return provider === 'google' || provider === 'apple' ? provider : 'other'+ }+ return ENDPOINT_METHODS[path] ?? null+}++/**+ * Where an account signs in from. Each new session is written down with how it was made, so the+ * account's owner can read its sign-ins and sessions, and a sign-in from an address the account+ * never used before is told to its email; the first sign-in an account makes is not.+ */+export function createSignInActivity(+ database: Kysely<CloudDatabase>,+ email?: AuthenticationEmailService+) {+ return {+ /** Writes down a session an endpoint just issued, and mails a sign-in from a new address. */+ async record(+ issued: {+ session: {+ id: string+ userId: string+ ipAddress?: string | null+ userAgent?: string | null+ }+ user: { email: string; name: string }+ },+ method: CloudSignInMethod+ ): Promise<void> {+ const { session, user } = issued+ // Confirming a new email address issues the session it was confirmed in again.+ const recorded = await database+ .selectFrom('signIn')+ .select('id')+ .where('sessionId', '=', session.id)+ .executeTakeFirst()+ if (recorded) return+ const ipAddress = session.ipAddress || null+ const [known, earlier] = await Promise.all([+ ipAddress+ ? database+ .selectFrom('signIn')+ .select('id')+ .where('userId', '=', session.userId)+ .where('ipAddress', '=', ipAddress)+ .executeTakeFirst()+ : undefined,+ database+ .selectFrom('signIn')+ .select('id')+ .where('userId', '=', session.userId)+ .executeTakeFirst()+ ])+ const id = crypto.randomUUID()+ const signedInAt = new Date()+ await database+ .insertInto('signIn')+ .values({+ id,+ userId: session.userId,+ sessionId: session.id,+ method,+ ipAddress,+ userAgent: session.userAgent || null,+ createdAt: signedInAt+ })+ .execute()+ if (!email || !earlier || known || !ipAddress) return+ await email.sendNewSignIn({+ email: user.email,+ name: user.name,+ signInId: id,+ signedInAt,+ ipAddress,+ ...describeUserAgent(session.userAgent),+ desktop: method === 'desktop'+ })+ },++ /** The account's sessions that have not expired, newest activity first. */+ async sessions(userId: string, currentSessionId: string): Promise<CloudAccountSession[]> {+ const rows = await database+ .selectFrom('session')+ .leftJoin('signIn', 'signIn.sessionId', 'session.id')+ .select([+ 'session.id',+ 'session.ipAddress',+ 'session.userAgent',+ 'session.createdAt',+ 'session.updatedAt',+ 'session.expiresAt',+ 'signIn.method'+ ])+ .where('session.userId', '=', userId)+ .where('session.expiresAt', '>', new Date())+ .orderBy('session.updatedAt', 'desc')+ .execute()+ return rows.map((row) => ({+ id: row.id,+ current: row.id === currentSessionId,+ method: row.method ?? null,+ ipAddress: row.ipAddress || null,+ ...describeUserAgent(row.userAgent),+ createdAt: dateString(row.createdAt) ?? '',+ lastActiveAt: dateString(row.updatedAt) ?? '',+ expiresAt: dateString(row.expiresAt) ?? ''+ }))+ },++ async signIns(userId: string, limit = SIGN_IN_HISTORY_LIMIT): Promise<CloudSignIn[]> {+ const rows = await database+ .selectFrom('signIn')+ .select(['id', 'method', 'ipAddress', 'userAgent', 'createdAt'])+ .where('userId', '=', userId)+ .orderBy('createdAt', 'desc')+ .limit(limit)+ .execute()+ return rows.map((row) => ({+ id: row.id,+ method: row.method,+ ipAddress: row.ipAddress,+ ...describeUserAgent(row.userAgent),+ createdAt: dateString(row.createdAt) ?? ''+ }))+ }+ }+}++export type SignInActivity = ReturnType<typeof createSignInActivity>++/**+ * Better Auth's side of account activity. After an endpoint issues a session, Better Auth hands+ * it to hooks as `newSession`; two-step sign-in clears it until the second step, so only+ * sessions someone can use are written down. Adding a passkey is told to its owner.+ */+export function accountActivity(+ activity: SignInActivity,+ onPasskeyAdded: (user: { id: string; email: string; name: string }) => Promise<void>+): BetterAuthPlugin {+ return {+ id: 'openpencil-account-activity',+ hooks: {+ after: [+ {+ matcher: (context) => signInMethod(context) !== null,+ handler: createAuthMiddleware(async (context) => {+ const issued = context.context.newSession+ const method = signInMethod(context)+ if (issued && method) await activity.record(issued, method)+ })+ },+ {+ matcher: (context) => context.path === '/passkey/verify-registration',+ handler: createAuthMiddleware(async (context) => {+ const user = context.context.session?.user+ if (user && !isAPIError(context.context.returned)) await onPasskeyAdded(user)+ })+ }+ ]+ }+ }+}diff --git a/packages/cloud/src/server/auth/adapter.ts b/packages/cloud/src/server/auth/adapter.tsindex 16a84db75..e9a963201 100644--- a/packages/cloud/src/server/auth/adapter.ts+++ b/packages/cloud/src/server/auth/adapter.ts@@ -1,15 +1,6 @@+import type { CloudAccountSession, CloudSignIn } from '#cloud/contract'import type { CloudActor } from '#cloud/server/auth/session'-export type CloudAdminUser = {- id: string- name: string- email: string- role?: string- banned: boolean | null- banReason?: string | null- createdAt: Date-}-export type CloudMFAStatus = {required: booleanenabled: boolean@@ -25,9 +16,18 @@ export type CloudIdentity = {userId: stringemail: stringname: string+ image?: string | nulldeploymentRole?: 'user' | 'admin'}+export type CloudAccountProfile = {+ id: string+ name: string+ email: string+ image: string | null+ createdAt: Date+}+export type CloudAuthenticationMethodRecord = {id: stringproviderId: string@@ -48,10 +48,6 @@ export interface CloudAuthAdapter {input: { provider: 'google' | 'apple'; callbackURL: string }): Promise<string>unlinkAuthenticationMethod(headers: Headers, methodId: string): Promise<void>- listUsers(- headers: Headers,- query?: { searchValue?: string; limit?: number; offset?: number }- ): Promise<{ users: CloudAdminUser[]; total: number }>banUser(headers: Headers, userId: string, reason?: string): Promise<void>unbanUser(headers: Headers, userId: string): Promise<void>revokeUserSessions(headers: Headers, userId: string): Promise<void>@@ -67,6 +63,17 @@ export interface CloudAuthAdapter {disableTOTP(headers: Headers, password?: string): Promise<void>listPasskeys(headers: Headers): Promise<Array<{ id: string; name?: string; createdAt: Date }>>deletePasskey(headers: Headers, id: string): Promise<void>+ /** Whether the server can confirm a new email address, which changing one needs. */+ emailChangeAvailable: boolean+ profile(headers: Headers): Promise<CloudAccountProfile | null>+ updateProfile(headers: Headers, input: { name: string }): Promise<void>+ /** Sends the confirmation to the new address and tells the old one which address it is. */+ changeEmail(headers: Headers, input: { newEmail: string; callbackURL: string }): Promise<void>+ sessions(headers: Headers): Promise<CloudAccountSession[] | null>+ /** Ends one of the person's other sessions; their current one ends by signing out. */+ revokeSession(headers: Headers, sessionId: string): Promise<void>+ revokeOtherSessions(headers: Headers): Promise<void>+ signIns(headers: Headers): Promise<CloudSignIn[] | null>migrate: () => Promise<void>schemaVersion: string}diff --git a/packages/cloud/src/server/auth/email.ts b/packages/cloud/src/server/auth/email.tsindex 128284918..9e3b33d52 100644--- a/packages/cloud/src/server/auth/email.ts+++ b/packages/cloud/src/server/auth/email.ts@@ -1,3 +1,4 @@+import type { TwoStepChange } from '#cloud/email'import type { TransactionalEmailService } from '#cloud/server/email'import { sha256 } from '@noble/hashes/sha2.js'import { bytesToHex, utf8ToBytes } from '@noble/hashes/utils.js'@@ -8,6 +9,7 @@ export type AuthenticationEmailService = {name: stringurl: stringtoken: string+ purpose?: 'account' | 'change'}): Promise<void>sendPasswordReset(input: {email: string@@ -21,6 +23,29 @@ export type AuthenticationEmailService = {userId: stringurl: string}): Promise<void>+ /** Tells the address being replaced which address is taking over, before it confirms. */+ sendEmailChangeRequested(input: {+ email: string+ name: string+ userId: string+ newEmail: string+ }): Promise<void>+ sendNewSignIn(input: {+ email: string+ name: string+ signInId: string+ signedInAt: Date+ ipAddress: string | null+ browser: string | null+ system: string | null+ desktop: boolean+ }): Promise<void>+ sendTwoStepChanged(input: {+ email: string+ name: string+ userId: string+ change: TwoStepChange+ }): Promise<void>}function tokenHash(value: string): string {@@ -37,7 +62,7 @@ export function createAuthenticationEmailService(idempotencyKey: `email-verification/${input.email.toLowerCase()}/${tokenHash(input.token)}`,kind: 'email-verification',recipientEmail: input.email,- payload: { name: input.name, actionURL: input.url }+ payload: { name: input.name, actionURL: input.url, purpose: input.purpose }})},async sendPasswordReset(input) {@@ -55,6 +80,46 @@ export function createAuthenticationEmailService(recipientEmail: input.email,payload: { name: input.name, actionURL: new URL('/auth/sign-in', publicURL).href }})+ },+ async sendEmailChangeRequested(input) {+ await email.enqueue({+ idempotencyKey: `email-change-requested/${input.userId}/${crypto.randomUUID()}`,+ kind: 'email-change-requested',+ recipientEmail: input.email,+ payload: {+ name: input.name,+ newEmail: input.newEmail,+ actionURL: new URL('/account/sessions', publicURL).href+ }+ })+ },+ async sendNewSignIn(input) {+ await email.enqueue({+ idempotencyKey: `new-sign-in/${input.signInId}`,+ kind: 'new-sign-in',+ recipientEmail: input.email,+ payload: {+ name: input.name,+ signedInAt: input.signedInAt.toISOString(),+ ipAddress: input.ipAddress,+ browser: input.browser,+ system: input.system,+ desktop: input.desktop,+ actionURL: new URL('/account/sessions', publicURL).href+ }+ })+ },+ async sendTwoStepChanged(input) {+ await email.enqueue({+ idempotencyKey: `two-step-changed/${input.userId}/${crypto.randomUUID()}`,+ kind: 'two-step-changed',+ recipientEmail: input.email,+ payload: {+ name: input.name,+ change: input.change,+ actionURL: new URL('/account/security', publicURL).href+ }+ })}}}diff --git a/packages/cloud/src/server/auth/factory.ts b/packages/cloud/src/server/auth/factory.tsindex c06ff8155..a42772bdb 100644--- a/packages/cloud/src/server/auth/factory.ts+++ b/packages/cloud/src/server/auth/factory.ts@@ -15,6 +15,7 @@ import {import { importPKCS8, SignJWT } from 'jose'import type { Kysely } from 'kysely'+import { accountActivity, createSignInActivity } from './activity'import type { CloudAuthAdapter } from './adapter'import type { AuthenticationEmailService } from './email'import { createMFAAssuranceService } from './mfa-assurance'@@ -139,6 +140,9 @@ export function createBetterAuthAdapter(): CloudAuthAdapter {const authenticationEmail = runtime.emailconst assurance = createMFAAssuranceService(database, config)+ const activity = createSignInActivity(database, authenticationEmail)+ // A new address is confirmed through a link sent to it, so changing one needs email delivery.+ const emailChangeAvailable = Boolean(config.emailPasswordEnabled && authenticationEmail)const auth = betterAuth({appName: 'OpenPencil Cloud',baseURL: config.publicURL,@@ -223,14 +227,19 @@ export function createBetterAuthAdapter(// Signing in unverified only says so; people ask for another link with Send again.sendOnSignIn: false,autoSignInAfterVerification: true,+ // A change of address sends the link to the new address as `user.email`, on the+ // account it already confirmed; a new account has not confirmed one yet. This runs+ // inside sign-up's transaction, so it must not query the database itself.sendVerificationEmail: ({ user, url, token }) =>authenticationEmail.sendVerification({email: user.email,name: user.name,url,- token+ token,+ purpose: user.emailVerified ? 'change' : 'account'}),afterEmailVerification: async (user) => {+ await enrollment.followEmailChange(user.id, user.email)if (config.enrollmentMode === 'approval') {await enrollment.request({ email: user.email, name: user.name })}@@ -239,6 +248,7 @@ export function createBetterAuthAdapter(}: undefined,user: {+ changeEmail: { enabled: emailChangeAvailable },validateUserInfo: ({ source }) => {if (source.action === 'create-user' && config.enrollmentMode === 'closed') {return { error: 'enrollment_closed', errorDescription: 'Cloud enrollment is closed' }@@ -292,7 +302,9 @@ export function createBetterAuthAdapter(deviceAuthorization({verificationUri: new URL('/auth/device', config.publicURL).href,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'))],socialProviders: socialProviders(config),trustedOrigins: [@@ -313,10 +325,44 @@ export function createBetterAuthAdapter(userId: session.user.id,email: session.user.email,name: session.user.name,+ image: session.user.image ?? null,deploymentRole: deploymentRole(session.user)}}+ /** The signed-in person, read past the cookie cache, for changes about their own account. */+ const currentSession = (headers: Headers) =>+ auth.api.getSession({ headers, query: { disableCookieCache: true } })++ /** The current session when it signed in recently enough to change how the account is reached. */+ async function freshSession(headers: Headers) {+ const session = await currentSession(headers)+ const createdAt = session?.session.createdAt+ if (+ !session ||+ !createdAt ||+ Date.now() - new Date(createdAt).getTime() >= ACCOUNT_SECURITY_FRESH_AGE_SECONDS * 1000+ ) {+ throw APIError.from('FORBIDDEN', {+ code: 'SESSION_NOT_FRESH',+ message: 'Session is not fresh'+ })+ }+ return session+ }++ async function notifyTwoStep(+ user: { id: string; email: string; name: string },+ change: Parameters<AuthenticationEmailService['sendTwoStepChanged']>[0]['change']+ ): Promise<void> {+ await authenticationEmail?.sendTwoStepChanged({+ email: user.email,+ name: user.name,+ userId: user.id,+ change+ })+ }+return {handler: async (request) => {const path = new URL(request.url).pathname@@ -365,17 +411,7 @@ export function createBetterAuthAdapter(}},async startSocialLink(headers, input) {- const session = await auth.api.getSession({ headers, query: { disableCookieCache: true } })- const createdAt = session?.session.createdAt- if (- !createdAt ||- Date.now() - new Date(createdAt).getTime() >= ACCOUNT_SECURITY_FRESH_AGE_SECONDS * 1000- ) {- throw APIError.from('FORBIDDEN', {- code: 'SESSION_NOT_FRESH',- message: 'Session is not fresh'- })- }+ await freshSession(headers)const response = await auth.api.linkSocialAccount({headers,body: {@@ -390,22 +426,6 @@ export function createBetterAuthAdapter(async unlinkAuthenticationMethod(headers, methodId) {await auth.api.unlinkAccount({ headers, body: { accountId: methodId } })},- async listUsers(headers, query) {- // Paging by offset needs a stable order, or people skip or repeat between pages.- const page = {- limit: query?.limit,- offset: query?.offset,- // Better Auth sorts by one field, so accounts created in the same millisecond, such as a- // bulk import, can trade places between pages; ordinary sign-ups never collide.- sortBy: 'createdAt',- sortDirection: 'asc' as const- }- const listQuery = query?.searchValue- ? { ...page, searchValue: query.searchValue, searchField: 'email' as const }- : page- const response = await auth.api.listUsers({ headers, query: listQuery })- return { users: response.users, total: response.total }- },async banUser(headers, userId, reason) {await auth.api.banUser({ headers, body: { userId, banReason: reason } })},@@ -440,7 +460,21 @@ export function createBetterAuthAdapter(return { totpURI: response.totpURI, backupCodes: response.backupCodes }},async verifyTOTP(headers, code) {- return verifySecondFactor(auth, config, database, assurance, headers, code, 'totp')+ const before = await currentSession(headers)+ const response = await verifySecondFactor(+ auth,+ config,+ database,+ assurance,+ headers,+ code,+ 'totp'+ )+ // The first code from a new authenticator is what turns it on.+ if (before && !('twoFactorEnabled' in before.user && before.user.twoFactorEnabled === true)) {+ await notifyTwoStep(before.user, 'authenticator-on')+ }+ return response},async verifyRecoveryCode(headers, code) {return verifySecondFactor(auth, config, database, assurance, headers, code, 'recovery-code')@@ -450,6 +484,8 @@ export function createBetterAuthAdapter(},async disableTOTP(headers, password) {await auth.api.disableTwoFactor({ headers, body: { password } })+ const session = await currentSession(headers)+ if (session) await notifyTwoStep(session.user, 'authenticator-off')},async listPasskeys(headers) {return (await auth.api.listPasskeys({ headers })).map((item) => ({@@ -460,6 +496,68 @@ export function createBetterAuthAdapter(},async deletePasskey(headers, id) {await auth.api.deletePasskey({ headers, body: { id } })+ const session = await currentSession(headers)+ if (session) await notifyTwoStep(session.user, 'passkey-removed')+ },+ emailChangeAvailable,+ async profile(headers) {+ const session = await currentSession(headers)+ if (!session) return null+ return {+ id: session.user.id,+ name: session.user.name,+ email: session.user.email,+ image: session.user.image ?? null,+ createdAt: new Date(session.user.createdAt)+ }+ },+ async updateProfile(headers, input) {+ await auth.api.updateUser({ headers, body: { name: input.name } })+ },+ async changeEmail(headers, input) {+ const session = await freshSession(headers)+ if (session.user.email === input.newEmail) {+ throw APIError.from('BAD_REQUEST', {+ code: 'EMAIL_UNCHANGED',+ message: 'Email is the same'+ })+ }+ await auth.api.changeEmail({ headers, body: input })+ await authenticationEmail?.sendEmailChangeRequested({+ email: session.user.email,+ name: session.user.name,+ userId: session.user.id,+ newEmail: input.newEmail+ })+ },+ async sessions(headers) {+ const session = await currentSession(headers)+ if (!session) return null+ return activity.sessions(session.user.id, session.session.id)+ },+ async revokeSession(headers, sessionId) {+ const session = await currentSession(headers)+ if (!session) throw APIError.fromStatus('UNAUTHORIZED')+ if (session.session.id === sessionId) {+ throw APIError.from('BAD_REQUEST', {+ code: 'CURRENT_SESSION',+ message: 'Sign out to end this session'+ })+ }+ const target = await database+ .selectFrom('session')+ .select('token')+ .where('id', '=', sessionId)+ .where('userId', '=', session.user.id)+ .executeTakeFirst()+ if (target) await auth.api.revokeSession({ headers, body: { token: target.token } })+ },+ async revokeOtherSessions(headers) {+ await auth.api.revokeOtherSessions({ headers })+ },+ async signIns(headers) {+ const session = await currentSession(headers)+ return session ? activity.signIns(session.user.id) : null},schemaVersion: BETTER_AUTH_SCHEMA_VERSION,async migrate() {diff --git a/packages/cloud/src/server/auth/index.ts b/packages/cloud/src/server/auth/index.tsindex 057d1f06f..574910907 100644--- a/packages/cloud/src/server/auth/index.ts+++ b/packages/cloud/src/server/auth/index.ts@@ -1,4 +1,5 @@export { createAccountAuthenticationService, type AccountAuthenticationService } from './account'+export { createSignInActivity, type SignInActivity } from './activity'export type { CloudAuthAdapter } from './adapter'export { createAuthenticationEmailService, type AuthenticationEmailService } from './email'export { createMFAAssuranceService, type MFAAssuranceService } from './mfa-assurance'diff --git a/packages/cloud/src/server/auth/mfa-assurance.ts b/packages/cloud/src/server/auth/mfa-assurance.tsindex 31575bd03..9439b699a 100644--- a/packages/cloud/src/server/auth/mfa-assurance.ts+++ b/packages/cloud/src/server/auth/mfa-assurance.ts@@ -16,7 +16,7 @@ export function createMFAAssuranceService(method: 'totp' | 'recovery-code' | 'passkey'}): Promise<void> {await database- .insertInto('cloudMfaAssurance')+ .insertInto('mfaAssurance').values({ ...input, verifiedAt: new Date() }).onConflict((conflict) =>conflict.column('sessionId').doUpdateSet({ method: input.method, verifiedAt: new Date() })@@ -31,7 +31,7 @@ export function createMFAAssuranceService(passkeyCount: number}): Promise<CloudMFAStatus> {const assurance = await database- .selectFrom('cloudMfaAssurance')+ .selectFrom('mfaAssurance').select('verifiedAt').where('sessionId', '=', input.sessionId).where('userId', '=', input.userId)diff --git a/packages/cloud/src/server/auth/user-agent.ts b/packages/cloud/src/server/auth/user-agent.tsnew file mode 100644index 000000000..49f8bbf52--- /dev/null+++ b/packages/cloud/src/server/auth/user-agent.ts@@ -0,0 +1,16 @@+import Bowser from 'bowser'+import { compact } from 'es-toolkit'++/** The browser and system a user agent names, as words for a person: `Chrome 141`, `macOS`. */+export function describeUserAgent(userAgent: string | null | undefined): {+ browser: string | null+ system: string | null+} {+ if (!userAgent) return { browser: null, system: null }+ const { browser, os } = Bowser.parse(userAgent)+ const version = browser.version?.split('.', 1)[0]+ return {+ browser: browser.name ? compact([browser.name, version]).join(' ') : null,+ system: os.name || null+ }+}diff --git a/packages/cloud/src/server/db/migrate.ts b/packages/cloud/src/server/db/migrate.tsindex 59df1bde3..c02766f24 100644--- a/packages/cloud/src/server/db/migrate.ts+++ b/packages/cloud/src/server/db/migrate.ts@@ -24,6 +24,8 @@ import * as workspaceInvitations from './migrations/020_workspace_invitations'import * as documentVersions from './migrations/021_document_versions'import * as entitlementExternalVersion from './migrations/022_entitlement_external_version'import * as documentImages from './migrations/023_document_images'+import * as accountActivity from './migrations/024_account_activity'+import * as tableNames from './migrations/025_table_names'import type { CloudDatabase } from './tables'const migrations: Record<string, Migration> = {@@ -49,7 +51,9 @@ const migrations: Record<string, Migration> = {'020_workspace_invitations': workspaceInvitations,'021_document_versions': documentVersions,'022_entitlement_external_version': entitlementExternalVersion,- '023_document_images': documentImages+ '023_document_images': documentImages,+ '024_account_activity': accountActivity,+ '025_table_names': tableNames}class CloudMigrationProvider implements MigrationProvider {@@ -108,7 +112,7 @@ async function migrateAuthSchema(migration: CloudAuthMigration): Promise<void> {const recorded = await database- .selectFrom('cloudAuthSchema')+ .selectFrom('authSchemaVersion').select('version').where('id', '=', 'better-auth').executeTakeFirst()@@ -138,7 +142,7 @@ async function migrateAuthSchema(}await database- .insertInto('cloudAuthSchema')+ .insertInto('authSchemaVersion').values({ id: 'better-auth', version: migration.schemaVersion, updatedAt: new Date() }).execute()}diff --git a/packages/cloud/src/server/db/migrations/018_authentication_mfa.ts b/packages/cloud/src/server/db/migrations/018_authentication_mfa.tsindex b1c5eecd8..cd14b8160 100644--- a/packages/cloud/src/server/db/migrations/018_authentication_mfa.ts+++ b/packages/cloud/src/server/db/migrations/018_authentication_mfa.ts@@ -1,13 +1,14 @@import { CURRENT_TIMESTAMP } from '#cloud/server/db/expressions'-import type { CloudDatabase } from '#cloud/server/db/tables'import type { Kysely } from 'kysely'+import type { LegacyAuthSchemaDatabase } from './helpers'+async function tableNames(database: Kysely<unknown>): Promise<Set<string>> {return new Set((await database.introspection.getTables()).map((table) => table.name))}export async function up(database: Kysely<unknown>): Promise<void> {- const cloud = database as Kysely<CloudDatabase>+ const cloud = database as Kysely<LegacyAuthSchemaDatabase>const tables = await tableNames(database)await database.schema.createTable('cloud_mfa_assurance')diff --git a/packages/cloud/src/server/db/migrations/019_better_auth_account_issuer.ts b/packages/cloud/src/server/db/migrations/019_better_auth_account_issuer.tsindex a0cb676aa..5a18f3869 100644--- a/packages/cloud/src/server/db/migrations/019_better_auth_account_issuer.ts+++ b/packages/cloud/src/server/db/migrations/019_better_auth_account_issuer.ts@@ -1,6 +1,7 @@-import type { CloudDatabase } from '#cloud/server/db/tables'import type { Kysely } from 'kysely'+import type { LegacyAuthSchemaDatabase } from './helpers'+/** The unique index Better Auth 1.7.0 through 1.7.2 created on `account (issuer, accountId)`. */const ISSUER_INDEX = 'account_issuer_accountId_uidx'@@ -11,7 +12,7 @@ const ISSUER_INDEX = 'account_issuer_accountId_uidx'* column itself is left for a later cleanup.*/export async function up(database: Kysely<unknown>): Promise<void> {- const cloud = database as Kysely<CloudDatabase>+ const cloud = database as Kysely<LegacyAuthSchemaDatabase>const account = (await database.introspection.getTables()).find((table) => table.name === 'account')@@ -31,7 +32,7 @@ export async function up(database: Kysely<unknown>): Promise<void> {}export async function down(database: Kysely<unknown>): Promise<void> {- const cloud = database as Kysely<CloudDatabase>+ const cloud = database as Kysely<LegacyAuthSchemaDatabase>await cloud.updateTable('cloudAuthSchema').set({ version: '1.7.2+mfa.1', updatedAt: new Date() })diff --git a/packages/cloud/src/server/db/migrations/024_account_activity.ts b/packages/cloud/src/server/db/migrations/024_account_activity.tsnew file mode 100644index 000000000..8bbc2e5c4--- /dev/null+++ b/packages/cloud/src/server/db/migrations/024_account_activity.ts@@ -0,0 +1,66 @@+import { CURRENT_TIMESTAMP } from '#cloud/server/db/expressions'+import type { Kysely } from 'kysely'++import { replaceCheckConstraint } from './helpers'++const emailKinds = [+ 'document-invitation',+ 'workspace-invitation',+ 'enrollment-requested',+ 'admin-enrollment-notification',+ 'enrollment-approved',+ 'enrollment-rejected',+ 'enrollment-revoked',+ 'email-verification',+ 'password-reset',+ 'password-changed'+]++/**+ * Every sign-in an account makes, so its owner can read where it was used and hear about one from+ * an address it never signed in from; a session keeps the row of the sign-in that made it, which+ * names how it was made. The security notices that follow get their own email kinds.+ */+export async function up(database: Kysely<unknown>): Promise<void> {+ await database.schema+ .createTable('sign_in')+ .addColumn('id', 'uuid', (column) => column.primaryKey())+ // Better Auth's tables may come after this migration, so the account is not a foreign key.+ .addColumn('user_id', 'uuid', (column) => column.notNull())+ .addColumn('session_id', 'uuid')+ .addColumn('method', 'text', (column) => column.notNull())+ .addColumn('ip_address', 'text')+ .addColumn('user_agent', 'text')+ .addColumn('created_at', 'timestamptz', (column) =>+ column.notNull().defaultTo(CURRENT_TIMESTAMP)+ )+ .execute()+ await database.schema+ .createIndex('sign_in_user_index')+ .on('sign_in')+ .columns(['user_id', 'created_at'])+ .execute()+ await database.schema+ .createIndex('sign_in_session_index')+ .on('sign_in')+ .column('session_id')+ .execute()+ await replaceCheckConstraint(+ database,+ 'transactional_email',+ 'transactional_email_kind_check',+ 'kind',+ [...emailKinds, 'email-change-requested', 'new-sign-in', 'two-step-changed']+ )+}++export async function down(database: Kysely<unknown>): Promise<void> {+ await replaceCheckConstraint(+ database,+ 'transactional_email',+ 'transactional_email_kind_check',+ 'kind',+ emailKinds+ )+ await database.schema.dropTable('sign_in').execute()+}diff --git a/packages/cloud/src/server/db/migrations/025_table_names.ts b/packages/cloud/src/server/db/migrations/025_table_names.tsnew file mode 100644index 000000000..8fde9b0d6--- /dev/null+++ b/packages/cloud/src/server/db/migrations/025_table_names.ts@@ -0,0 +1,58 @@+import { sql, type Kysely } from 'kysely'++/**+ * OpenPencil's tables beside Better Auth's lose the `cloud_` prefix the rest never had; only the+ * rate limit keeps a qualifier, since Better Auth has a `rate_limit` of its own. Their keys,+ * checks, and indexes follow, so no name keeps the old prefix.+ */+const TABLES = [+ ['cloud_enrollment', 'enrollment'],+ ['cloud_mfa_assurance', 'mfa_assurance'],+ ['cloud_admin_audit_event', 'admin_audit_event'],+ ['cloud_auth_schema', 'auth_schema_version'],+ ['cloud_rate_limit', 'api_rate_limit']+] as const++const CONSTRAINTS = [+ ['enrollment', 'cloud_enrollment_pkey', 'enrollment_pkey'],+ ['enrollment', 'cloud_enrollment_email_normalized_key', 'enrollment_email_normalized_key'],+ ['enrollment', 'cloud_enrollment_status_check', 'enrollment_status_check'],+ ['mfa_assurance', 'cloud_mfa_assurance_pkey', 'mfa_assurance_pkey'],+ ['admin_audit_event', 'cloud_admin_audit_event_pkey', 'admin_audit_event_pkey'],+ ['auth_schema_version', 'cloud_auth_schema_pkey', 'auth_schema_version_pkey'],+ ['api_rate_limit', 'cloud_rate_limit_pkey', 'api_rate_limit_pkey']+] as const++const INDEXES = [+ ['cloud_enrollment_status_index', 'enrollment_status_index'],+ ['cloud_admin_audit_created_index', 'admin_audit_event_created_index']+] as const++async function rename(database: Kysely<unknown>, direction: 'up' | 'down'): Promise<void> {+ const forward = direction === 'up'+ if (forward) {+ for (const [from, to] of TABLES) await database.schema.alterTable(from).renameTo(to).execute()+ }+ // Tables carry their new names while their constraints and indexes are renamed either way.+ for (const [table, from, to] of CONSTRAINTS) {+ await database.schema+ .alterTable(table)+ .renameConstraint(forward ? from : to, forward ? to : from)+ .execute()+ }+ for (const [from, to] of INDEXES) {+ const [source, target] = forward ? [from, to] : [to, from]+ await sql`alter index ${sql.id(source)} rename to ${sql.id(target)}`.execute(database)+ }+ if (!forward) {+ for (const [from, to] of TABLES) await database.schema.alterTable(to).renameTo(from).execute()+ }+}++export async function up(database: Kysely<unknown>): Promise<void> {+ await rename(database, 'up')+}++export async function down(database: Kysely<unknown>): Promise<void> {+ await rename(database, 'down')+}diff --git a/packages/cloud/src/server/db/migrations/helpers.ts b/packages/cloud/src/server/db/migrations/helpers.tsindex 5a9325cbc..2a302087d 100644--- a/packages/cloud/src/server/db/migrations/helpers.ts+++ b/packages/cloud/src/server/db/migrations/helpers.ts@@ -1,4 +1,5 @@import { checkColumnIn, CURRENT_TIMESTAMP } from '#cloud/server/db/expressions'+import type { AuthSchemaVersionTable } from '#cloud/server/db/tables'import type { CreateTableBuilder, Kysely } from 'kysely'export async function addCheckConstraint(@@ -69,3 +70,9 @@ export function addInvitationColumns<.addColumn('accepted_at', 'timestamptz').addColumn('revoked_at', 'timestamptz')}++/**+ * The Better Auth schema record under the name it had before `025_table_names`, for the+ * migrations that ran while it was `cloud_auth_schema`; they must keep emitting the same SQL.+ */+export type LegacyAuthSchemaDatabase = { cloudAuthSchema: AuthSchemaVersionTable }diff --git a/packages/cloud/src/server/db/tables.ts b/packages/cloud/src/server/db/tables.tsindex bb2226ccb..b81aacfd7 100644--- a/packages/cloud/src/server/db/tables.ts+++ b/packages/cloud/src/server/db/tables.ts@@ -1,5 +1,5 @@import type { EnrollmentStatus } from '#cloud/admin/enrollment/service'-import type { DocumentPermission, WorkspaceRole } from '#cloud/contract'+import type { CloudSignInMethod, DocumentPermission, WorkspaceRole } from '#cloud/contract'import type { TransactionalEmailKind, TransactionalEmailPayloadByKind } from '#cloud/email'import type { Account, Session } from 'better-auth'import type { ColumnType, Generated, Insertable, Selectable, Updateable } from 'kysely'@@ -171,7 +171,8 @@ export interface AuthUserTable {banned: Generated<boolean | null>banReason: Generated<string | null>banExpires: TimestampColumn | null- twoFactorEnabled: Generated<boolean>+ /** Unset on accounts that never turned two-step sign-in on. */+ twoFactorEnabled: Generated<boolean | null>createdAt: TimestampColumnupdatedAt: TimestampColumn}@@ -200,13 +201,23 @@ export interface PasskeyTable {aaguid: string | null}-export interface CloudMFAAssuranceTable {+export interface MFAAssuranceTable {sessionId: stringuserId: stringmethod: 'totp' | 'recovery-code' | 'passkey'verifiedAt: TimestampColumn}+export interface SignInTable {+ id: string+ userId: string+ sessionId: string | null+ method: CloudSignInMethod+ ipAddress: string | null+ userAgent: string | null+ createdAt: TimestampColumn+}+export interface DocumentCollaborationStateTable {documentId: stringroomEpoch: number@@ -275,7 +286,7 @@ export interface TransactionalEmailTable {export type TransactionalEmailPayload = TransactionalEmailPayloadByKind[TransactionalEmailKind]-export interface CloudEnrollmentTable {+export interface EnrollmentTable {id: stringemailNormalized: stringname: string | null@@ -289,14 +300,14 @@ export interface CloudEnrollmentTable {approvedUserId: string | null}-export interface CloudRateLimitTable {+export interface APIRateLimitTable {keyHash: stringwindowStartedAt: TimestampColumnrequestCount: Generated<number>updatedAt: TimestampColumn}-export interface CloudAdminAuditEventTable {+export interface AdminAuditEventTable {id: stringactorUserId: stringaction: string@@ -306,7 +317,7 @@ export interface CloudAdminAuditEventTable {createdAt: TimestampColumn}-export interface CloudAuthSchemaTable {+export interface AuthSchemaVersionTable {id: stringversion: stringupdatedAt: TimestampColumn@@ -317,12 +328,13 @@ export interface CloudDatabase {session: SessiontwoFactor: TwoFactorTablepasskey: PasskeyTable- cloudMfaAssurance: CloudMFAAssuranceTable+ mfaAssurance: MFAAssuranceTable+ signIn: SignInTableuser: AuthUserTable- cloudAuthSchema: CloudAuthSchemaTable- cloudEnrollment: CloudEnrollmentTable- cloudRateLimit: CloudRateLimitTable- cloudAdminAuditEvent: CloudAdminAuditEventTable+ authSchemaVersion: AuthSchemaVersionTable+ enrollment: EnrollmentTable+ apiRateLimit: APIRateLimitTable+ adminAuditEvent: AdminAuditEventTableworkspace: WorkspaceTableworkspaceMember: WorkspaceMemberTableworkspaceInvitation: WorkspaceInvitationTablediff --git a/packages/cloud/src/server/rate-limit/cleanup.ts b/packages/cloud/src/server/rate-limit/cleanup.tsindex 66f33c1c6..b4c88445f 100644--- a/packages/cloud/src/server/rate-limit/cleanup.ts+++ b/packages/cloud/src/server/rate-limit/cleanup.ts@@ -5,7 +5,7 @@ export function createRateLimitCleanupService(database: Kysely<CloudDatabase>) {return {async cleanupExpired(before: Date): Promise<number> {const result = await database- .deleteFrom('cloudRateLimit')+ .deleteFrom('apiRateLimit').where('windowStartedAt', '<', before).executeTakeFirst()return Number(result.numDeletedRows)diff --git a/packages/cloud/src/server/rate-limit/postgres.ts b/packages/cloud/src/server/rate-limit/postgres.tsindex 9ca6060b3..ff45e4372 100644--- a/packages/cloud/src/server/rate-limit/postgres.ts+++ b/packages/cloud/src/server/rate-limit/postgres.ts@@ -33,7 +33,7 @@ export class PostgresRateLimitStore implements Store {Math.floor(now.getTime() / this.windowMs) * this.windowMs + this.windowMs)const row = await this.database- .insertInto('cloudRateLimit')+ .insertInto('apiRateLimit').values({keyHash: this.hash(key),windowStartedAt: new Date(resetTime.getTime() - this.windowMs),@@ -44,8 +44,8 @@ export class PostgresRateLimitStore implements Store {conflict.column('keyHash').doUpdateSet((expression) => ({requestCount: expression.case()- .whenRef('cloudRateLimit.windowStartedAt', '=', 'excluded.windowStartedAt')- .then(expression('cloudRateLimit.requestCount', '+', 1))+ .whenRef('apiRateLimit.windowStartedAt', '=', 'excluded.windowStartedAt')+ .then(expression('apiRateLimit.requestCount', '+', 1)).else(1).end(),windowStartedAt: expression.ref('excluded.windowStartedAt'),@@ -62,7 +62,7 @@ export class PostgresRateLimitStore implements Store {async decrement(key: string): Promise<void> {await this.database- .updateTable('cloudRateLimit')+ .updateTable('apiRateLimit').set((expression) => ({requestCount: expression.fn('greatest', [expression('requestCount', '-', 1),@@ -74,6 +74,6 @@ export class PostgresRateLimitStore implements Store {}async resetKey(key: string): Promise<void> {- await this.database.deleteFrom('cloudRateLimit').where('keyHash', '=', this.hash(key)).execute()+ await this.database.deleteFrom('apiRateLimit').where('keyHash', '=', this.hash(key)).execute()}}diff --git a/packages/cloud/src/server/workspaces/members.ts b/packages/cloud/src/server/workspaces/members.tsindex 968a85611..4a2232bd9 100644--- a/packages/cloud/src/server/workspaces/members.ts+++ b/packages/cloud/src/server/workspaces/members.ts@@ -86,6 +86,8 @@ function invitationContract(row: {id: stringemailNormalized: stringrole: WorkspaceRole+ invitedBy: string+ inviterName: string | nullinvitedAt: Date | stringexpiresAt: Date | string}): WorkspaceInvitation {@@ -93,6 +95,7 @@ function invitationContract(row: {id: row.id,email: row.emailNormalized,role: row.role,+ invitedBy: { id: row.invitedBy, name: row.inviterName },invitedAt: dateString(row.invitedAt) ?? '',expiresAt: dateString(row.expiresAt) ?? ''}@@ -166,6 +169,76 @@ export function createWorkspaceMemberService(return cloudInvitationURL(options.publicURL, invitationId, token)}+ /** Invites someone by email; a newer invitation to the same address replaces the older. */+ async function invite(+ userId: string,+ workspaceId: string,+ input: CreateWorkspaceInvitationInput+ ): Promise<CreatedWorkspaceInvitation> {+ const workspace = await requireAdmin(userId, workspaceId)+ const existing = await memberUsers(workspaceId)+ .select('workspaceMember.userId')+ .where((expression) =>+ expression(expression.fn('lower', [expression.ref('user.email')]), '=', input.email)+ )+ .executeTakeFirst()+ if (existing) throw new WorkspaceAlreadyMemberError()+ const inviter = await database+ .selectFrom('user')+ .select('name')+ .where('id', '=', userId)+ .executeTakeFirst()+ const id = crypto.randomUUID()+ const token = randomHex(INVITATION_SECRET_BYTES)+ const expiresAt = new Date(Date.now() + INVITATION_LIFETIME_MS)+ const url = acceptanceURL(id, token)+ const row = await database.transaction().execute(async (transaction) => {+ await transaction+ .updateTable('workspaceInvitation')+ .set({ revokedAt: new Date() })+ .where('workspaceId', '=', workspaceId)+ .where('emailNormalized', '=', input.email)+ .where('acceptedAt', 'is', null)+ .where('revokedAt', 'is', null)+ .execute()+ const inserted = await transaction+ .insertInto('workspaceInvitation')+ .values({+ id,+ workspaceId,+ emailNormalized: input.email,+ role: input.role,+ tokenHash: hashCapability(token),+ invitedBy: userId,+ expiresAt,+ acceptedAt: null,+ revokedAt: null+ })+ .returning(['id', 'emailNormalized', 'role', 'invitedBy', 'invitedAt', 'expiresAt'])+ .executeTakeFirstOrThrow()+ await options.email?.enqueue(+ {+ idempotencyKey: `workspace-invitation/${id}`,+ kind: 'workspace-invitation',+ recipientEmail: input.email,+ payload: {+ inviterName: inviter?.name ?? 'An OpenPencil user',+ workspaceName: workspace.name,+ role: input.role,+ expiresAt: expiresAt.toISOString(),+ acceptanceURL: url+ }+ },+ transaction+ )+ return inserted+ })+ return {+ invitation: invitationContract({ ...row, inviterName: inviter?.name ?? null }),+ acceptanceURL: url+ }+ }+return {async rename(userId: string, workspaceId: string, name: string): Promise<WorkspaceSummary> {await requireAdmin(userId, workspaceId)@@ -185,7 +258,8 @@ export function createWorkspaceMemberService('workspaceMember.role','workspaceMember.createdAt','user.name',- 'user.email'+ 'user.email',+ 'user.image']).orderBy('workspaceMember.createdAt').execute()@@ -193,12 +267,29 @@ export function createWorkspaceMemberService(workspace.role === 'admin'? await database.selectFrom('workspaceInvitation')- .select(['id', 'emailNormalized', 'role', 'invitedAt', 'expiresAt'])- .where('workspaceId', '=', workspaceId)- .where('acceptedAt', 'is', null)- .where('revokedAt', 'is', null)- .where('expiresAt', '>', new Date())- .orderBy('invitedAt')+ .leftJoin('user', (join) =>+ join.on((expression) =>+ expression(+ expression.cast(expression.ref('user.id'), 'text'),+ '=',+ expression.ref('workspaceInvitation.invitedBy')+ )+ )+ )+ .select([+ 'workspaceInvitation.id',+ 'workspaceInvitation.emailNormalized',+ 'workspaceInvitation.role',+ 'workspaceInvitation.invitedAt',+ 'workspaceInvitation.expiresAt',+ 'workspaceInvitation.invitedBy',+ 'user.name as inviterName'+ ])+ .where('workspaceInvitation.workspaceId', '=', workspaceId)+ .where('workspaceInvitation.acceptedAt', 'is', null)+ .where('workspaceInvitation.revokedAt', 'is', null)+ .where('workspaceInvitation.expiresAt', '>', new Date())+ .orderBy('workspaceInvitation.invitedAt').execute(): []return {@@ -206,6 +297,7 @@ export function createWorkspaceMemberService(userId: member.userId,name: member.name,email: member.email,+ image: member.image,role: member.role,joinedAt: dateString(member.createdAt) ?? ''})),@@ -213,71 +305,28 @@ export function createWorkspaceMemberService(}},- /** Invites someone by email; a newer invitation to the same address replaces the older. */- async invite(+ invite,++ /** Sends a waiting invitation again with a new link; the old link stops working. */+ async resendInvitation(userId: string,workspaceId: string,- input: CreateWorkspaceInvitationInput+ invitationId: string): Promise<CreatedWorkspaceInvitation> {- const workspace = await requireAdmin(userId, workspaceId)- const existing = await memberUsers(workspaceId)- .select('workspaceMember.userId')- .where((expression) =>- expression(expression.fn('lower', [expression.ref('user.email')]), '=', input.email)- )- .executeTakeFirst()- if (existing) throw new WorkspaceAlreadyMemberError()- const inviter = await database- .selectFrom('user')- .select('name')- .where('id', '=', userId)+ await requireAdmin(userId, workspaceId)+ const invitation = await database+ .selectFrom('workspaceInvitation')+ .select(['emailNormalized', 'role'])+ .where('id', '=', invitationId)+ .where('workspaceId', '=', workspaceId)+ .where('acceptedAt', 'is', null)+ .where('revokedAt', 'is', null).executeTakeFirst()- const id = crypto.randomUUID()- const token = randomHex(INVITATION_SECRET_BYTES)- const expiresAt = new Date(Date.now() + INVITATION_LIFETIME_MS)- const url = acceptanceURL(id, token)- const row = await database.transaction().execute(async (transaction) => {- await transaction- .updateTable('workspaceInvitation')- .set({ revokedAt: new Date() })- .where('workspaceId', '=', workspaceId)- .where('emailNormalized', '=', input.email)- .where('acceptedAt', 'is', null)- .where('revokedAt', 'is', null)- .execute()- const inserted = await transaction- .insertInto('workspaceInvitation')- .values({- id,- workspaceId,- emailNormalized: input.email,- role: input.role,- tokenHash: hashCapability(token),- invitedBy: userId,- expiresAt,- acceptedAt: null,- revokedAt: null- })- .returning(['id', 'emailNormalized', 'role', 'invitedAt', 'expiresAt'])- .executeTakeFirstOrThrow()- await options.email?.enqueue(- {- idempotencyKey: `workspace-invitation/${id}`,- kind: 'workspace-invitation',- recipientEmail: input.email,- payload: {- inviterName: inviter?.name ?? 'An OpenPencil user',- workspaceName: workspace.name,- role: input.role,- expiresAt: expiresAt.toISOString(),- acceptanceURL: url- }- },- transaction- )- return inserted+ if (!invitation) throw new WorkspaceNotFoundError()+ return invite(userId, workspaceId, {+ email: invitation.emailNormalized,+ role: invitation.role})- return { invitation: invitationContract(row), acceptanceURL: url }},async revokeInvitation(diff --git a/packages/cloud/src/server/workspaces/routes.ts b/packages/cloud/src/server/workspaces/routes.tsindex bbec95f34..faa39cc7a 100644--- a/packages/cloud/src/server/workspaces/routes.ts+++ b/packages/cloud/src/server/workspaces/routes.ts@@ -68,6 +68,17 @@ export function createWorkspaceRoutes((context) => context.req.method !== 'POST'))+ // Resending mails the invitation again, so it counts against the same budget as sending.+ router.use(+ '/:workspaceId/invitations/:invitationId/resend',+ createActorRateLimiter(+ rateLimit.database,+ rateLimit.secret,+ CLOUD_RATE_LIMITS.invitationMutation,+ () => false,+ (context) => context.req.param('workspaceId') ?? 'unknown'+ )+ )router.use('/:workspaceId/invitations',createActorRateLimiter(@@ -142,6 +153,17 @@ export function createWorkspaceRoutes()))+ .post('/:workspaceId/invitations/:invitationId/resend', (context) =>+ memberRoute(context, async () =>+ context.json(+ await members.resendInvitation(+ context.get('actor').userId,+ context.req.param('workspaceId'),+ context.req.param('invitationId')+ )+ )+ )+ ).delete('/:workspaceId/invitations/:invitationId', (context) =>memberRoute(context, async () => {await members.revokeInvitation(diff --git a/packages/cloud/tests/client/portal/client.test.ts b/packages/cloud/tests/client/portal/client.test.tsindex d0f7f0c29..a9b7e7e25 100644--- a/packages/cloud/tests/client/portal/client.test.ts+++ b/packages/cloud/tests/client/portal/client.test.ts@@ -44,6 +44,11 @@ describe('Cloud portal client', () => {await expect(forbidden.session()).rejects.toEqual(expect.objectContaining({ kind: 'authorization-required' }))+ const refused = createCloudPortalClient({+ baseURL: 'https://cloud.example.com',+ fetch: async () => Response.json({ error: { code: 'forbidden' } }, { status: 403 })+ })+ await expect(refused.users({})).rejects.toMatchObject({ kind: 'authorization-required' })const domain = createCloudPortalClient({baseURL: 'https://cloud.example.com',fetch: async () => Response.json({ error: { code: 'last_admin_required' } }, { status: 400 })@@ -100,7 +105,7 @@ describe('Cloud portal client', () => {])requests.length = 0await client.enrollments('pending').catch(() => undefined)- await client.users('ada').catch(() => undefined)+ await client.users({ search: 'ada' }).catch(() => undefined)await client.accountStatus().catch(() => undefined)expect(requests.map((request) => request.url)).toEqual(['https://cloud.example.com/api/admin/enrollments?status=pending',diff --git a/packages/cloud/tests/email/render.test.ts b/packages/cloud/tests/email/render.test.tsnew file mode 100644index 000000000..a5441d7c3--- /dev/null+++ b/packages/cloud/tests/email/render.test.ts@@ -0,0 +1,48 @@+import { describe, expect, test } from 'bun:test'++import { renderTransactionalEmail, type TransactionalEmailContent } from '#cloud/email'++const ACCOUNT_URL = 'https://cloud.example.com/account/sessions'++const notices: TransactionalEmailContent[] = [+ {+ kind: 'email-change-requested',+ payload: { name: 'Ada', newEmail: '[email protected]', actionURL: ACCOUNT_URL }+ },+ {+ kind: 'new-sign-in',+ payload: {+ name: 'Ada',+ signedInAt: '2026-10-24T12:00:00.000Z',+ ipAddress: '203.0.113.9',+ browser: 'Chrome 141',+ system: 'macOS',+ desktop: false,+ actionURL: ACCOUNT_URL+ }+ },+ ...(['authenticator-on', 'passkey-removed', 'reset-by-administrator'] as const).map(+ (change): TransactionalEmailContent => ({+ kind: 'two-step-changed',+ payload: { name: 'Ada', change, actionURL: ACCOUNT_URL }+ })+ )+]++describe('security notices', () => {+ test.each(notices.map((content) => [content.kind, content] as const))(+ '%s renders a subject and links back to the account',+ async (_kind, content) => {+ const rendered = await renderTransactionalEmail(content)+ expect(rendered.subject.length).toBeGreaterThan(0)+ expect(rendered.html).toContain(ACCOUNT_URL)+ expect(rendered.text).toContain(ACCOUNT_URL)+ }+ )++ test('a new sign-in names the address it came from', async () => {+ const content = notices.find((notice) => notice.kind === 'new-sign-in')+ if (!content) throw new Error('missing notice')+ expect((await renderTransactionalEmail(content)).text).toContain('203.0.113.9')+ })+})diff --git a/packages/cloud/tests/helpers/account-authentication.ts b/packages/cloud/tests/helpers/account-authentication.tsindex 5926c9ee7..435df277a 100644--- a/packages/cloud/tests/helpers/account-authentication.ts+++ b/packages/cloud/tests/helpers/account-authentication.ts@@ -1,5 +1,10 @@import { createCloudTestDatabase } from '#cloud-tests/helpers/database'-import { createCloudApp, createBetterAuthAdapter, parseCloudServerConfig } from '#cloud/server'+import {+ createCloudApp,+ createBetterAuthAdapter,+ parseCloudServerConfig,+ type AuthenticationEmailService+} from '#cloud/server'export const accountAuthenticationConfig = parseCloudServerConfig({deployment: 'self-hosted',@@ -24,12 +29,20 @@ const ignore = async (): Promise<void> => {await Promise.resolve()}+/** Security notices for an account email service whose test does not read them. */+export const ignoredSecurityNotices = {+ sendEmailChangeRequested: ignore,+ sendNewSignIn: ignore,+ sendTwoStepChanged: ignore+}+export function accountAuthenticationRequest(path: string,body?: object,- cookie?: string+ cookie?: string,+ init: { headers?: Record<string, string> } = {}): Request {- const headers = new Headers()+ 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), {@@ -70,17 +83,21 @@ export async function createAccountAuthenticationFixture(options: {config?: typeof accountAuthenticationConfigonPasswordChanged?: () => void+ /** Account emails the test reads; the rest go nowhere. */+ email?: Partial<AuthenticationEmailService>} = {}) {const config = options.config ?? accountAuthenticationConfigconst runtime = await createCloudTestDatabase()const auth = createBetterAuthAdapter(config, runtime.database, undefined, {email: {+ ...ignoredSecurityNotices,sendVerification: ignore,sendPasswordReset: ignore,async sendPasswordChanged() {options.onPasswordChanged?.()- }+ },+ ...options.email}})return {@@ -99,7 +116,7 @@ export async function approveAccount(input: { email: string; name: string; userId: string }): Promise<void> {await database- .insertInto('cloudEnrollment')+ .insertInto('enrollment').values({id: crypto.randomUUID(),emailNormalized: input.email,diff --git a/packages/cloud/tests/integration/admin/email/service.test.ts b/packages/cloud/tests/integration/admin/email/service.test.tsindex 1d7e6a906..edb6311a2 100644--- a/packages/cloud/tests/integration/admin/email/service.test.ts+++ b/packages/cloud/tests/integration/admin/email/service.test.ts@@ -14,7 +14,7 @@ describe('admin email regeneration', () => {const runtime = await createCloudTestDatabase()try {await runtime.database- .insertInto('cloudEnrollment')+ .insertInto('enrollment').values({id: crypto.randomUUID(),emailNormalized: '[email protected]',@@ -55,7 +55,7 @@ describe('admin email regeneration', () => {expect(rows[1]).toMatchObject({ kind: 'enrollment-approved', status: 'pending' })expect(await runtime.database- .selectFrom('cloudAdminAuditEvent')+ .selectFrom('adminAuditEvent').select('action').executeTakeFirstOrThrow()).toEqual({ action: 'email.regenerated' })@@ -94,7 +94,7 @@ describe('admin email regeneration', () => {const runtime = await createCloudTestDatabase()try {await runtime.database- .insertInto('cloudEnrollment')+ .insertInto('enrollment').values({id: crypto.randomUUID(),emailNormalized: '[email protected]',diff --git a/packages/cloud/tests/integration/admin/enrollment/service.test.ts b/packages/cloud/tests/integration/admin/enrollment/service.test.tsindex 53fe92630..463daa69d 100644--- a/packages/cloud/tests/integration/admin/enrollment/service.test.ts+++ b/packages/cloud/tests/integration/admin/enrollment/service.test.ts@@ -45,7 +45,7 @@ describe('Cloud enrollment integration', () => {expect(await enrollment.statusForEmail('[email protected]')).toBe('approved')expect(await runtime.database- .selectFrom('cloudAdminAuditEvent')+ .selectFrom('adminAuditEvent').select('action').executeTakeFirstOrThrow()).toEqual({ action: 'enrollment.approved' })@@ -108,7 +108,7 @@ describe('Cloud enrollment integration', () => {expect(Math.max(...results.map((result) => result.totalHits))).toBe(20)expect(await runtime.database- .selectFrom('cloudRateLimit')+ .selectFrom('apiRateLimit').select(['keyHash', 'requestCount']).executeTakeFirstOrThrow()).toMatchObject({diff --git a/packages/cloud/tests/integration/admin/users/service.test.ts b/packages/cloud/tests/integration/admin/users/service.test.tsindex d257f11b9..8f0357a4c 100644--- a/packages/cloud/tests/integration/admin/users/service.test.ts+++ b/packages/cloud/tests/integration/admin/users/service.test.ts@@ -1,7 +1,8 @@import { describe, expect, test } from 'bun:test'+import { ignoredSecurityNotices } from '#cloud-tests/helpers/account-authentication'import { createCloudTestDatabase } from '#cloud-tests/helpers/database'-import { createAdminUserService } from '#cloud/server'+import { createAdminAuditService, createAdminUserService } from '#cloud/server'const ADMIN_ID = '11111111-1111-4111-8111-111111111111'const USER_ID = '22222222-2222-4222-8222-222222222222'@@ -13,9 +14,6 @@ function complete(): Promise<void> {function authAdapter() {return {schemaVersion: 'test',- async listUsers() {- return { users: [], total: 0 }- },async banUser() {return complete()},@@ -73,6 +71,20 @@ function authAdapter() {async deletePasskey() {return complete()},+ emailChangeAvailable: false,+ async profile() {+ return null+ },+ updateProfile: complete,+ changeEmail: complete,+ async sessions() {+ return null+ },+ revokeSession: complete,+ revokeOtherSessions: complete,+ async signIns() {+ return null+ },async migrate() {return complete()}@@ -132,4 +144,195 @@ describe('deployment admin user safety', () => {await runtime.close()}})++ test('lists accounts by filter and search, with counts and what each one uses', async () => {+ const runtime = await createCloudTestDatabase()+ try {+ const SUSPENDED_ID = '33333333-3333-4333-8333-333333333333'+ await runtime.database+ .insertInto('user')+ .values([+ {+ id: ADMIN_ID,+ name: 'Admin',+ email: '[email protected]',+ emailVerified: true,+ image: null,+ role: 'admin',+ banned: false,+ twoFactorEnabled: true,+ createdAt: new Date(Date.UTC(2026, 0, 1))+ },+ {+ id: USER_ID,+ name: 'Grace Hopper',+ email: '[email protected]',+ emailVerified: true,+ image: 'https://images.example.com/grace.png',+ role: 'user',+ banned: false,+ createdAt: new Date(Date.UTC(2026, 0, 2))+ },+ {+ id: SUSPENDED_ID,+ name: 'Suspended_Person',+ email: '[email protected]',+ emailVerified: true,+ image: null,+ role: 'user',+ banned: true,+ banReason: 'Spam',+ createdAt: new Date(Date.UTC(2026, 0, 3))+ }+ ])+ .execute()+ await runtime.database+ .insertInto('passkey')+ .values({+ id: crypto.randomUUID(),+ name: 'Laptop',+ publicKey: 'key',+ userId: SUSPENDED_ID,+ credentialID: 'credential',+ counter: 0,+ deviceType: 'singleDevice',+ backedUp: false,+ transports: null,+ createdAt: new Date(),+ aaguid: null+ })+ .execute()+ const workspaceId = crypto.randomUUID()+ await runtime.database+ .insertInto('workspace')+ .values({ id: workspaceId, name: 'Studio', slug: 'studio', createdBy: USER_ID })+ .execute()+ await runtime.database+ .insertInto('workspaceMember')+ .values({ workspaceId, userId: USER_ID, role: 'admin' })+ .execute()+ const service = createAdminUserService(runtime.database, authAdapter())++ const everyone = await service.list()+ expect(everyone.users.map((user) => user.email)).toEqual([+ '[email protected]',+ '[email protected]',+ ])+ expect(everyone.counts).toEqual({+ all: 3,+ administrators: 1,+ suspended: 1,+ 'without-two-step': 1+ })+ expect(everyone.users.map((user) => user.twoStep)).toEqual([true, false, true])+ expect(everyone.users[1]).toMatchObject({+ image: 'https://images.example.com/grace.png',+ workspaceCount: 1,+ lastActiveAt: null+ })+ expect((await service.list({ filter: 'suspended' })).users).toEqual([+ expect.objectContaining({ id: SUSPENDED_ID, banReason: 'Spam' })+ ])+ expect(+ (await service.list({ filter: 'without-two-step' })).users.map((user) => user.id)+ ).toEqual([USER_ID])++ // A search matches names as well as emails, and its wildcards are plain characters.+ const searched = await service.list({ search: 'hopper' })+ expect(searched.users.map((user) => user.id)).toEqual([USER_ID])+ expect(searched.counts.all).toBe(1)+ expect((await service.list({ search: '_' })).users.map((user) => user.id)).toEqual([+ SUSPENDED_ID+ ])+ expect((await service.list({ limit: 1, offset: 1 })).users.map((user) => user.id)).toEqual([+ USER_ID+ ])++ const detail = await service.detail(USER_ID)+ expect(detail?.workspaces).toEqual([+ expect.objectContaining({ id: workspaceId, name: 'Studio', role: 'admin', memberCount: 1 })+ ])+ expect(await service.detail(crypto.randomUUID())).toBeNull()+ } finally {+ await runtime.close()+ }+ })++ test('resets another account’s two-step sign-in 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: 'Locked Out',+ email: '[email protected]',+ emailVerified: true,+ image: null,+ role: 'user',+ banned: false,+ twoFactorEnabled: true+ }+ ])+ .execute()+ await runtime.database+ .insertInto('twoFactor')+ .values({+ id: crypto.randomUUID(),+ secret: 'secret',+ backupCodes: 'codes',+ userId: USER_ID+ })+ .execute()+ const notices: string[] = []+ const service = createAdminUserService(runtime.database, authAdapter(), {+ notify: {+ ...ignoredSecurityNotices,+ sendVerification: complete,+ sendPasswordReset: complete,+ sendPasswordChanged: complete,+ async sendTwoStepChanged(input) {+ notices.push(`${input.email}:${input.change}`)+ }+ }+ })+ await expect(service.resetTwoStep(ADMIN_ID, ADMIN_ID)).rejects.toThrow('themselves')++ await service.resetTwoStep(ADMIN_ID, USER_ID)+ const user = await runtime.database+ .selectFrom('user')+ .select('twoFactorEnabled')+ .where('id', '=', USER_ID)+ .executeTakeFirstOrThrow()+ expect(user.twoFactorEnabled).toBe(false)+ const factors = await runtime.database+ .selectFrom('twoFactor')+ .select('id')+ .where('userId', '=', USER_ID)+ .execute()+ expect(factors).toEqual([])+ expect(notices).toEqual(['[email protected]:reset-by-administrator'])+ const events = await createAdminAuditService(runtime.database).list()+ expect(events).toEqual([+ expect.objectContaining({+ action: 'user.two-step-reset',+ actor: { id: ADMIN_ID, name: 'Admin' },+ subject: { type: 'user', id: USER_ID, name: 'Locked Out' }+ })+ ])+ } finally {+ await runtime.close()+ }+ })})diff --git a/packages/cloud/tests/integration/server/account/routes.test.ts b/packages/cloud/tests/integration/server/account/routes.test.tsnew file mode 100644index 000000000..59e99a26f--- /dev/null+++ b/packages/cloud/tests/integration/server/account/routes.test.ts@@ -0,0 +1,395 @@+import { describe, expect, test } from 'bun:test'++import {+ accountAuthenticationConfig,+ accountAuthenticationRequest,+ authenticationCookie,+ createAccountAuthenticationFixture,+ createVerifiedCredentialAccount+} from '#cloud-tests/helpers/account-authentication'+import { responseJSON } from '#cloud-tests/helpers/response'+import {+ accountSecurityErrorResponseSchema,+ cloudAccountSessionsResponseSchema,+ cloudAccountStatusResponseSchema,+ cloudProfileResponseSchema,+ cloudSignInsResponseSchema+} from '#cloud/contract'+import { base32 } from '@better-auth/utils/base32'+import { createOTP } from '@better-auth/utils/otp'+import * as v from 'valibot'++const PASSWORD = 'a sufficiently long password'+const CHROME =+ 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36'+const config = { ...accountAuthenticationConfig, authTrustedIPHeaders: ['x-forwarded-for'] }++async function signIn(+ fixture: Awaited<ReturnType<typeof createAccountAuthenticationFixture>>,+ email: string,+ headers: Record<string, string> = {}+): Promise<string> {+ const response = await fixture.app.fetch(+ accountAuthenticationRequest(+ '/api/auth/sign-in/email',+ { email, password: PASSWORD },+ undefined,+ { headers }+ )+ )+ return authenticationCookie(response)+}++describe('account profile', () => {+ test('reads and renames the signed-in person', async () => {+ const fixture = await createAccountAuthenticationFixture()+ try {+ const account = await createVerifiedCredentialAccount(fixture, {+ email: '[email protected]',+ name: 'Profile Person',+ password: PASSWORD,+ approved: true+ })+ const read = async () =>+ (+ await responseJSON(+ await fixture.app.fetch(+ accountAuthenticationRequest('/api/account/profile', undefined, account.sessionCookie)+ ),+ cloudProfileResponseSchema+ )+ ).profile+ expect(await read()).toMatchObject({+ id: account.userId,+ name: 'Profile Person',+ email: '[email protected]',+ emailChangeAvailable: true+ })++ const renamed = await fixture.app.fetch(+ accountAuthenticationRequest(+ '/api/account/profile',+ { name: ' Renamed Person ' },+ account.sessionCookie+ )+ )+ expect(renamed.status).toBe(200)+ expect((await read()).name).toBe('Renamed Person')+ const blank = await fixture.app.fetch(+ accountAuthenticationRequest('/api/account/profile', { name: ' ' }, account.sessionCookie)+ )+ expect(blank.status).toBe(400)+ const signedOut = await fixture.app.fetch(+ accountAuthenticationRequest('/api/account/profile')+ )+ expect(signedOut.status).toBe(401)+ } finally {+ await fixture.close()+ }+ })++ test('changes the email once the new address confirms it, keeping the approval', async () => {+ const notices: Array<{ email: string; newEmail: string }> = []+ const verifications: Array<{ email: string; url: string; purpose?: string }> = []+ const fixture = await createAccountAuthenticationFixture({+ email: {+ async sendEmailChangeRequested(input) {+ notices.push(input)+ },+ async sendVerification(input) {+ verifications.push(input)+ }+ }+ })+ try {+ const account = await createVerifiedCredentialAccount(fixture, {+ email: '[email protected]',+ name: 'Moving Person',+ password: PASSWORD,+ approved: true+ })+ const unchanged = await fixture.app.fetch(+ accountAuthenticationRequest(+ '/api/account/profile/email',+ { newEmail: '[email protected]', callbackURL: `${config.publicURL}/account` },+ account.sessionCookie+ )+ )+ expect(unchanged.status).toBe(400)+ expect((await responseJSON(unchanged, accountSecurityErrorResponseSchema)).error.code).toBe(+ 'email_unchanged'+ )++ const requested = await fixture.app.fetch(+ accountAuthenticationRequest(+ '/api/account/profile/email',+ { newEmail: '[email protected]', callbackURL: `${config.publicURL}/account` },+ account.sessionCookie+ )+ )+ expect(requested.status).toBe(200)+ expect(notices).toEqual([+ expect.objectContaining({ email: '[email protected]', newEmail: '[email protected]' })+ ])+ const verification = verifications.at(-1)+ expect(verification).toMatchObject({ email: '[email protected]', purpose: 'change' })+ const user = () =>+ fixture.database+ .selectFrom('user')+ .select('email')+ .where('id', '=', account.userId)+ .executeTakeFirstOrThrow()+ expect((await user()).email).toBe('[email protected]')++ await fixture.app.fetch(+ new Request(verification?.url ?? '', { headers: { Cookie: account.sessionCookie } })+ )+ expect((await user()).email).toBe('[email protected]')+ const enrollment = await fixture.database+ .selectFrom('enrollment')+ .select(['emailNormalized', 'status'])+ .where('approvedUserId', '=', account.userId)+ .executeTakeFirstOrThrow()+ expect(enrollment).toEqual({ emailNormalized: '[email protected]', status: 'approved' })+ const status = await responseJSON(+ await fixture.app.fetch(+ accountAuthenticationRequest(+ '/api/account/status',+ undefined,+ await signIn(fixture, '[email protected]')+ )+ ),+ cloudAccountStatusResponseSchema+ )+ expect(status.state).toBe('active')+ } finally {+ await fixture.close()+ }+ })++ test('asks a session that signed in a while ago to sign in again before changing email', async () => {+ const fixture = await createAccountAuthenticationFixture()+ try {+ const account = await createVerifiedCredentialAccount(fixture, {+ email: '[email protected]',+ name: 'Stale Person',+ password: PASSWORD,+ approved: true+ })+ await fixture.database+ .updateTable('session')+ .set({ createdAt: new Date(Date.now() - 60 * 60_000) })+ .where('userId', '=', account.userId)+ .execute()+ const response = await fixture.app.fetch(+ accountAuthenticationRequest(+ '/api/account/profile/email',+ { newEmail: '[email protected]', callbackURL: `${config.publicURL}/account` },+ account.sessionCookie+ )+ )+ expect(response.status).toBe(403)+ expect((await responseJSON(response, accountSecurityErrorResponseSchema)).error.code).toBe(+ 'session_not_fresh'+ )+ } finally {+ await fixture.close()+ }+ })+})++describe('account sessions and sign-ins', () => {+ test('lists sessions with how they signed in and ends the other ones', async () => {+ const fixture = await createAccountAuthenticationFixture({ config })+ try {+ const account = await createVerifiedCredentialAccount(fixture, {+ email: '[email protected]',+ name: 'Session Person',+ password: PASSWORD,+ approved: true+ })+ const other = await signIn(fixture, '[email protected]', {+ 'X-Forwarded-For': '203.0.113.9',+ 'User-Agent': CHROME+ })+ const list = async (cookie: string) =>+ (+ await responseJSON(+ await fixture.app.fetch(+ accountAuthenticationRequest('/api/account/sessions', undefined, cookie)+ ),+ cloudAccountSessionsResponseSchema+ )+ ).sessions+ const sessions = await list(account.sessionCookie)+ expect(sessions).toHaveLength(2)+ const current = sessions.find((session) => session.current)+ const elsewhere = sessions.find((session) => !session.current)+ expect(current?.method).toBe('password')+ expect(elsewhere).toMatchObject({+ method: 'password',+ ipAddress: '203.0.113.9',+ browser: 'Chrome 141',+ system: 'macOS'+ })++ const ownSession = await fixture.app.fetch(+ accountAuthenticationRequest(+ '/api/account/sessions/revoke',+ { sessionId: current?.id },+ account.sessionCookie+ )+ )+ expect(ownSession.status).toBe(400)+ expect((await responseJSON(ownSession, accountSecurityErrorResponseSchema)).error.code).toBe(+ 'current_session'+ )++ const revoked = await fixture.app.fetch(+ accountAuthenticationRequest(+ '/api/account/sessions/revoke',+ { sessionId: elsewhere?.id },+ account.sessionCookie+ )+ )+ expect(revoked.status).toBe(200)+ expect(await list(account.sessionCookie)).toHaveLength(1)+ const ended = await fixture.app.fetch(+ accountAuthenticationRequest('/api/account/sessions', undefined, other)+ )+ expect(ended.status).toBe(401)++ await signIn(fixture, '[email protected]')+ expect(await list(account.sessionCookie)).toHaveLength(2)+ await fixture.app.fetch(+ accountAuthenticationRequest(+ '/api/account/sessions/revoke-others',+ {},+ account.sessionCookie+ )+ )+ expect(await list(account.sessionCookie)).toEqual([+ expect.objectContaining({ current: true })+ ])+ } finally {+ await fixture.close()+ }+ })++ test('records sign-ins and emails one from an address the account never used', async () => {+ const alerts: Array<{ ipAddress: string | null; browser: string | null }> = []+ const fixture = await createAccountAuthenticationFixture({+ config,+ email: {+ async sendNewSignIn(input) {+ alerts.push(input)+ }+ }+ })+ try {+ const account = await createVerifiedCredentialAccount(fixture, {+ email: '[email protected]',+ name: 'Alert Person',+ password: PASSWORD,+ approved: true+ })+ // The account's first sign-in is the one that made it, so nobody is told about it.+ expect(alerts).toHaveLength(0)+ const from = { 'X-Forwarded-For': '198.51.100.4', 'User-Agent': CHROME }+ await signIn(fixture, '[email protected]', from)+ expect(alerts).toEqual([+ expect.objectContaining({ ipAddress: '198.51.100.4', browser: 'Chrome 141' })+ ])+ await signIn(fixture, '[email protected]', from)+ expect(alerts).toHaveLength(1)++ const signIns = (+ await responseJSON(+ await fixture.app.fetch(+ accountAuthenticationRequest('/api/account/sign-ins', undefined, account.sessionCookie)+ ),+ cloudSignInsResponseSchema+ )+ ).signIns+ expect(signIns).toHaveLength(3)+ expect(signIns.every((entry) => entry.method === 'password')).toBe(true)+ expect(signIns[0]?.ipAddress).toBe('198.51.100.4')+ } finally {+ await fixture.close()+ }+ })++ test('records a two-step sign-in once its second step is done', async () => {+ const changes: string[] = []+ const fixture = await createAccountAuthenticationFixture({+ config: { ...config, totpEnabled: true, recoveryCodesEnabled: true },+ email: {+ async sendTwoStepChanged(input) {+ changes.push(input.change)+ }+ }+ })+ try {+ const account = await createVerifiedCredentialAccount(fixture, {+ email: '[email protected]',+ name: 'Two Steps',+ password: PASSWORD,+ approved: true+ })+ const setup = await responseJSON(+ await fixture.app.fetch(+ accountAuthenticationRequest(+ '/api/account/mfa/totp/enable',+ { password: PASSWORD },+ account.sessionCookie+ )+ ),+ v.object({ totpURI: v.string() })+ )+ const secret = new TextDecoder().decode(+ base32.decode(new URL(setup.totpURI).searchParams.get('secret') ?? '')+ )+ const otp = createOTP(secret)+ await fixture.app.fetch(+ accountAuthenticationRequest(+ '/api/account/mfa/totp/verify',+ { code: await otp.totp() },+ account.sessionCookie+ )+ )+ expect(changes).toEqual(['authenticator-on'])+ const recorded = async () =>+ (+ await fixture.database+ .selectFrom('signIn')+ .select('method')+ .where('userId', '=', account.userId)+ .orderBy('createdAt')+ .execute()+ ).map((row) => row.method)+ const before = await recorded()++ const pending = await fixture.app.fetch(+ accountAuthenticationRequest('/api/auth/sign-in/email', {+ email: '[email protected]',+ password: PASSWORD+ })+ )+ expect(await recorded()).toEqual(before)+ const challenge = pending.headers+ .getSetCookie()+ .map((cookie) => cookie.split(';', 1)[0])+ .find((cookie) => cookie?.includes('two_factor'))+ await fixture.app.fetch(+ accountAuthenticationRequest(+ '/api/auth/two-factor/verify-totp',+ { code: await otp.totp() },+ challenge+ )+ )+ expect(await recorded()).toEqual([...before, 'two-step'])+ } finally {+ await fixture.close()+ }+ })+})diff --git a/packages/cloud/tests/integration/server/app.test.ts b/packages/cloud/tests/integration/server/app.test.tsindex 0cb2ebd36..721268491 100644--- a/packages/cloud/tests/integration/server/app.test.ts+++ b/packages/cloud/tests/integration/server/app.test.ts@@ -131,7 +131,7 @@ describe('createCloudApp', () => {})expect(await runtime.database- .selectFrom('cloudEnrollment')+ .selectFrom('enrollment').select(['emailNormalized', 'status']).executeTakeFirstOrThrow()).toEqual({ emailNormalized: '[email protected]', status: 'pending' })@@ -322,7 +322,7 @@ describe('createCloudApp', () => {expect(authCalls).toBe(8)expect(await runtime.database- .selectFrom('cloudRateLimit')+ .selectFrom('apiRateLimit').select(({ fn }) => fn.countAll<number>().as('count')).executeTakeFirstOrThrow()).toEqual({ count: 0 })diff --git a/packages/cloud/tests/integration/server/auth/account-methods.test.ts b/packages/cloud/tests/integration/server/auth/account-methods.test.tsindex 5504688e7..dd6e6861b 100644--- a/packages/cloud/tests/integration/server/auth/account-methods.test.ts+++ b/packages/cloud/tests/integration/server/auth/account-methods.test.ts@@ -95,7 +95,7 @@ describe('account authentication methods', () => {).toBe(401)await fixture.database- .insertInto('cloudEnrollment')+ .insertInto('enrollment').values({id: crypto.randomUUID(),emailNormalized: '[email protected]',diff --git a/packages/cloud/tests/integration/server/auth/email-password.test.ts b/packages/cloud/tests/integration/server/auth/email-password.test.tsindex 204d20c89..9093dbda9 100644--- a/packages/cloud/tests/integration/server/auth/email-password.test.ts+++ b/packages/cloud/tests/integration/server/auth/email-password.test.ts@@ -1,5 +1,6 @@import { describe, expect, test } from 'bun:test'+import { ignoredSecurityNotices } from '#cloud-tests/helpers/account-authentication'import { createCloudTestDatabase } from '#cloud-tests/helpers/database'import {createAuthenticationEmailService,@@ -31,7 +32,13 @@ const config = parseCloudServerConfig({s3SecretAccessKey: 'secret-key'})-async function runtime(authenticationEmail?: AuthenticationEmailService) {+/** The account emails a test watches; security notices go nowhere. */+type WatchedEmail = Pick<+ AuthenticationEmailService,+ 'sendVerification' | 'sendPasswordReset' | 'sendPasswordChanged'+>++async function runtime(authenticationEmail?: WatchedEmail) {const databaseRuntime = await createCloudTestDatabase()const email = createTransactionalEmailService(databaseRuntime.database, {encryptionSecret: config.authSecret,@@ -43,7 +50,9 @@ async function runtime(authenticationEmail?: AuthenticationEmailService) {})const auth = createBetterAuthAdapter(config, databaseRuntime.database, enrollment, {- email: authenticationEmail ?? createAuthenticationEmailService(email, config.publicURL)+ email: authenticationEmail+ ? { ...ignoredSecurityNotices, ...authenticationEmail }+ : createAuthenticationEmailService(email, config.publicURL)})return { ...databaseRuntime, auth, enrollment }}diff --git a/packages/cloud/tests/integration/server/db/auth-schema.test.ts b/packages/cloud/tests/integration/server/db/auth-schema.test.tsindex 9c1eb45a5..a4c2527bb 100644--- a/packages/cloud/tests/integration/server/db/auth-schema.test.ts+++ b/packages/cloud/tests/integration/server/db/auth-schema.test.ts@@ -2,6 +2,11 @@ import { describe, expect, test } from 'bun:test'import { createCloudDatabase, migrateCloudDatabase } from '#cloud/server'import { up as relaxAccountIssuer } from '#cloud/server/db/migrations/019_better_auth_account_issuer'+import {+ down as restoreTableNames,+ up as renameTables+} from '#cloud/server/db/migrations/025_table_names'+import type { LegacyAuthSchemaDatabase } from '#cloud/server/db/migrations/helpers'import { PGlite } from '@electric-sql/pglite'import { CamelCasePlugin, Kysely, sql } from 'kysely'import { PGliteDialect } from 'kysely-pglite-dialect'@@ -124,7 +129,7 @@ describe('Better Auth schema ledger', () => {await migrateCloudDatabase(database, migration)expect(runs).toBe(1)expect(- await database.selectFrom('cloudAuthSchema').selectAll().executeTakeFirstOrThrow()+ await database.selectFrom('authSchemaVersion').selectAll().executeTakeFirstOrThrow()).toMatchObject({ id: 'better-auth', version: '1.7.7+mfa.1' })} finally {await database.destroy()@@ -143,7 +148,7 @@ describe('Better Auth schema ledger', () => {}})expect(- await database.selectFrom('cloudAuthSchema').select('version').executeTakeFirstOrThrow()+ await database.selectFrom('authSchemaVersion').select('version').executeTakeFirstOrThrow()).toEqual({ version: '1.7.7+mfa.1' })} finally {await database.destroy()@@ -159,7 +164,7 @@ describe('Better Auth schema ledger', () => {migrateCloudDatabase(database, { schemaVersion: '1.7.2', run: async () => undefined })).rejects.toThrow('Existing Better Auth schema is incomplete')await database- .insertInto('cloudAuthSchema')+ .insertInto('authSchemaVersion').values({ id: 'better-auth', version: '1.7.2', updatedAt: new Date() }).execute()await expect(@@ -180,6 +185,9 @@ describe('Better Auth schema ledger', () => {})try {await migrateCloudDatabase(database)+ // The schema as 019 found it, before the tables lost their `cloud_` prefix.+ await restoreTableNames(untyped)+ const legacy = untyped as Kysely<LegacyAuthSchemaDatabase>await database.schema.createTable('account').addColumn('id', 'uuid', (column) => column.primaryKey())@@ -193,15 +201,16 @@ describe('Better Auth schema ledger', () => {.columns(['issuer', 'account_id']).unique().execute()- await database+ await legacy.insertInto('cloudAuthSchema').values({ id: 'better-auth', version: '1.7.2+mfa.1', updatedAt: new Date() }).execute()await relaxAccountIssuer(untyped)+ await renameTables(untyped)expect(- await database.selectFrom('cloudAuthSchema').select('version').executeTakeFirstOrThrow()+ await database.selectFrom('authSchemaVersion').select('version').executeTakeFirstOrThrow()).toEqual({ version: '1.7.7+mfa.1' })const account = (await database.introspection.getTables()).find((table) => table.name === 'account'diff --git a/packages/cloud/tests/integration/server/rate-limit/cleanup.test.ts b/packages/cloud/tests/integration/server/rate-limit/cleanup.test.tsindex 87a99a03a..25a5f4fa6 100644--- a/packages/cloud/tests/integration/server/rate-limit/cleanup.test.ts+++ b/packages/cloud/tests/integration/server/rate-limit/cleanup.test.ts@@ -8,7 +8,7 @@ describe('Cloud rate-limit cleanup', () => {const runtime = await createCloudTestDatabase()try {await runtime.database- .insertInto('cloudRateLimit')+ .insertInto('apiRateLimit').values([{ keyHash: 'old', windowStartedAt: new Date('2025-01-01'), requestCount: 1 },{ keyHash: 'active', windowStartedAt: new Date('2026-01-02'), requestCount: 1 }@@ -17,9 +17,9 @@ describe('Cloud rate-limit cleanup', () => {expect(await createRateLimitCleanupService(runtime.database).cleanupExpired(new Date('2026-01-01'))).toBe(1)- expect(- await runtime.database.selectFrom('cloudRateLimit').select('keyHash').execute()- ).toEqual([{ keyHash: 'active' }])+ expect(await runtime.database.selectFrom('apiRateLimit').select('keyHash').execute()).toEqual(+ [{ keyHash: 'active' }]+ )} finally {await runtime.close()}diff --git a/packages/cloud/tests/integration/server/workspaces/members.test.ts b/packages/cloud/tests/integration/server/workspaces/members.test.tsindex 716b55c42..97d4baf40 100644--- a/packages/cloud/tests/integration/server/workspaces/members.test.ts+++ b/packages/cloud/tests/integration/server/workspaces/members.test.ts@@ -213,6 +213,70 @@ describe('workspace members', () => {await runtime.close()}})+ test('resends a waiting invitation under a new link and names who sent it', async () => {+ const { runtime, as } = await testApp()+ try {+ const created = await responseJSON(+ await as(people.alice)('/api/workspaces', { method: 'POST', json: { name: 'Studio' } }),+ v.object({ workspace: v.object({ id: v.string() }) })+ )+ const workspaceId = created.workspace.id+ const first = await responseJSON(+ await as(people.alice)(`/api/workspaces/${workspaceId}/invitations`, {+ method: 'POST',+ json: { email: '[email protected]', role: 'viewer' }+ }),+ createdSchema+ )+ const resent = await responseJSON(+ await as(people.alice)(+ `/api/workspaces/${workspaceId}/invitations/${first.invitation.id}/resend`,+ { method: 'POST' }+ ),+ createdSchema+ )+ expect(resent.invitation).toMatchObject({ email: '[email protected]', role: 'viewer' })+ expect(resent.invitation.id).not.toBe(first.invitation.id)+ const listed = await responseJSON(+ await as(people.alice)(`/api/workspaces/${workspaceId}/members`),+ v.object({+ invitations: v.array(+ v.object({+ id: v.string(),+ invitedBy: v.object({ id: v.string(), name: v.nullable(v.string()) })+ })+ )+ })+ )+ expect(listed.invitations).toEqual([+ { id: resent.invitation.id, invitedBy: { id: people.alice.userId, name: 'Alice' } }+ ])++ const stale = await as(people.bob)(`/api/invitations/${first.invitation.id}/accept`, {+ method: 'POST',+ json: { token: new URL(first.acceptanceURL).hash.slice(1) }+ })+ expect(stale.status).toBe(404)+ const accepted = await as(people.bob)(`/api/invitations/${resent.invitation.id}/accept`, {+ method: 'POST',+ json: { token: new URL(resent.acceptanceURL).hash.slice(1) }+ })+ expect(accepted.status).toBe(200)++ const gone = await as(people.alice)(+ `/api/workspaces/${workspaceId}/invitations/${resent.invitation.id}/resend`,+ { method: 'POST' }+ )+ expect(gone.status).toBe(404)+ const notAdmin = await as(people.bob)(+ `/api/workspaces/${workspaceId}/invitations/${first.invitation.id}/resend`,+ { method: 'POST' }+ )+ expect(notAdmin.status).toBe(403)+ } finally {+ await runtime.close()+ }+ })test('deletes a workspace only once it holds no documents', async () => {const { runtime, as } = await testApp()try {diff --git a/packages/cloud/tests/server/api/router.test.ts b/packages/cloud/tests/server/api/router.test.tsindex 8931e8763..7a368e883 100644--- a/packages/cloud/tests/server/api/router.test.ts+++ b/packages/cloud/tests/server/api/router.test.ts@@ -123,6 +123,7 @@ function services() {list: notUsed,invite: notUsed,revokeInvitation: notUsed,+ resendInvitation: notUsed,updateRole: notUsed,remove: notUsed,delete: notUsed,diff --git a/packages/cloud/tests/server/auth/activity.test.ts b/packages/cloud/tests/server/auth/activity.test.tsnew file mode 100644index 000000000..5c6688ba7--- /dev/null+++ b/packages/cloud/tests/server/auth/activity.test.ts@@ -0,0 +1,32 @@+import { describe, expect, test } from 'bun:test'++import { signInMethod } from '#cloud/server/auth/activity'+import { describeUserAgent } from '#cloud/server/auth/user-agent'++describe('sign-in activity', () => {+ test('names how each Better Auth endpoint signed someone in', () => {+ expect(signInMethod({ path: '/sign-in/email' })).toBe('password')+ expect(signInMethod({ path: '/callback/:id', params: { id: 'google' } })).toBe('google')+ expect(signInMethod({ path: '/callback/:id', params: { id: 'apple' } })).toBe('apple')+ expect(signInMethod({ path: '/callback/:id', params: { id: 'github' } })).toBe('other')+ expect(signInMethod({ path: '/passkey/verify-authentication' })).toBe('passkey')+ expect(signInMethod({ path: '/two-factor/verify-totp' })).toBe('two-step')+ expect(signInMethod({ path: '/verify-email' })).toBe('email-link')+ expect(signInMethod({ path: '/device/token' })).toBe('desktop')+ })++ test('ignores endpoints that only refresh or change a session', () => {+ expect(signInMethod({ path: '/get-session' })).toBeNull()+ expect(signInMethod({ path: '/update-user' })).toBeNull()+ expect(signInMethod({})).toBeNull()+ })++ test('reads a browser and system from a user agent, and nothing from none', () => {+ expect(+ describeUserAgent(+ 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36 Edg/141.0.0.0'+ )+ ).toEqual({ browser: 'Microsoft Edge 141', system: 'Windows' })+ expect(describeUserAgent(null)).toEqual({ browser: null, system: null })+ })+})diff --git a/packages/docs/development/cloud.md b/packages/docs/development/cloud.mdindex ecd3b25ef..502cb9237 100644--- a/packages/docs/development/cloud.md+++ b/packages/docs/development/cloud.md@@ -124,6 +124,20 @@ Database rows use UUIDs. Capability secrets and invitation tokens are random hexdigests are stored, and they travel in URL fragments so they never reach access logs or `Referer`headers. Invitation continuations through OAuth are single-use compact JWE.+Every sign-in is recorded in `sign_in` with the session it made and how it was made. A Better+Auth plugin, `accountActivity` in `src/server/auth/activity.ts`, reads the session an endpoint+issued from the hook context's `newSession`, which two-step sign-in leaves empty until the second+step, and the method from the endpoint, as Better Auth's own `lastLoginMethod` does: a password,+Google or Apple, a passkey, a second step, an email link, or the desktop app's device code. A person's Sessions page lists their live sessions with+that method and the browser the server reads from the user agent, and their latest sign-ins. A+sign-in from an address the account was never signed in from is emailed to its owner, except the+account's first. Adding or removing an authenticator app or a passkey is emailed too, and so is+an administrator resetting them.++A new email address is confirmed from that address through Better Auth's change-email link, and+the old address is told which address is taking over. An approved enrollment follows the account+to its new address, so the approval stays with the account.+Collaboration tickets are signed, epoch-scoped JWTs naming the principal and permission. Rotating acapability secret keeps the current epoch; revoking access advances it so old tickets stop working.@@ -192,11 +206,18 @@ pending request that a deployment administrator approves or rejects; approval caDeployment administrators are separate from workspace administrators, and startup never grantseither role: the first operator is approved and promoted through the `admin` command.+The console's People list pages through accounts in sign-up order, searched by name or email and+filtered to administrators, suspended accounts, or accounts without two-step sign-in, with a count+for each filter. A person's page shows how they sign in, their workspaces, sessions, and recent+sign-ins. Administrators make and remove administrators, sign people out everywhere, suspend+with 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.+## PortalThe server shows its own pages on its public address: a welcome page, sign-in and sign-up, email-verification, password reset, two-step sign-in, desktop sign-in approval, account security, and the-administration console. They are a separate Vite entry, `cloud.html`, in the app project, so they+verification, password reset, two-step sign-in, desktop sign-in approval, account pages (profile,+sign-in and security, and sessions), and the administration console. They are a separate Vite entry, `cloud.html`, in the app project, so theyreuse the editor's components and theme without loading the editor. `bun run build:cloud` writesthem to `dist-cloud/` beside the editor itself, which every Cloud server serves at its root. Theeditor never embeds these pages; when it needs them, for a social provider or a second sign-in@@ -323,11 +344,11 @@ a Cron Trigger retries the rest; `email.transport = "none"` disables delivery.## Tests-| Level | Location | Needs |-| ----------- | ------------------------------------------------------- | ----------------------- |-| Unit | `packages/cloud/tests/{client,contract,runtime,server}` | nothing |-| Integration | `packages/cloud/tests/integration`, mirroring `src` | PGlite, in process |-| End-to-end | `packages/cloud/tests/e2e` | Docker Compose services |+| Level | Location | Needs |+| ----------- | ------------------------------------------------------------- | ----------------------- |+| Unit | `packages/cloud/tests/{client,contract,email,runtime,server}` | nothing |+| Integration | `packages/cloud/tests/integration`, mirroring `src` | PGlite, in process |+| End-to-end | `packages/cloud/tests/e2e` | Docker Compose services |`bun run test:cloud` type-checks the package and runs unit and integration tests. The end-to-endrunners start PostgreSQL and SeaweedFS (or Garage) in an isolated Compose project, exercise presigned@@ -468,3 +489,14 @@ no `server` parameter and no `/cloud` prefix, and the server has no separate edisend them to. Peer-to-peer rooms move to `/rooms/:id` so "share" names a shared document. Thecost is that a browser editor at any other address cannot keep a Cloud document in its addressbar; every server serves its own editor, and the desktop app gets links through `openpencil://`.++**2026-10 · Workspaces are deleted at once, not after a grace period.** GitLab keeps a deleted group+for 30 days so it can be restored; a Cloud workspace can only be deleted once it holds no+documents, and deleted documents already have their own retention, so a delay would protect+nothing but the name and members. Workspace settings stay in the editor's Members dialog, which+the desktop app reaches without leaving for a browser.++**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 a+qualifier (`api_rate_limit` beside its `rate_limit`). Migrations that shipped before the rename+type their queries against the names they ran with, so their SQL never changes.diff --git a/packages/docs/user-guide/openpencil-cloud.md b/packages/docs/user-guide/openpencil-cloud.mdindex ff9f22385..38c7ffbd4 100644--- a/packages/docs/user-guide/openpencil-cloud.md+++ b/packages/docs/user-guide/openpencil-cloud.md@@ -21,12 +21,22 @@ 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 page, where you change your password, two-step sign-in, and passkeys.+- **Account and security** in the server's **…** menu opens the server's own account pages. 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.The desktop app keeps its sign-in in the system credential store. In the browser, a sign-in through the server's page lasts as long as the server's session; a sign-in with a code follows **Settings → General → Remember API keys on this device**.+## Your Account++A 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.+- **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.++The server emails you when your account is signed in from an address it has never been signed in from, and when an authenticator app or a passkey is added or removed.+## Find Documents on HomeHome lists places in a sidebar: **Recent**, the workspaces of the server Home shows, **Shared with you**, and your storage bucket. On a phone the same places are in a menu above the documents. With more than one server connected, choose which one Home shows with **Show on Home** in Settings. At the server's own editor address, OpenPencil opens on Home, in your first workspace until you pick another place.@@ -35,12 +45,11 @@ A workspace lists its documents with where each one stands, how much of the work## Work in a Team Workspace-Every account starts with a workspace of its own. To work with a team, select **+** beside **OpenPencil Cloud** in Home's sidebar, name the workspace, and you administer it. **Members** in the workspace's header lists who is in it:+Every account starts with a workspace of its own. To work with a team, select **+** beside **OpenPencil Cloud** in Home's sidebar, name the workspace, and you administer it. **Members** in the workspace's header has three tabs:-- Admins rename the workspace, invite people by email as an admin, editor, or viewer, change roles, and remove people. Editors and admins change documents; viewers only look.-- An invitation arrives by email. If the server doesn't send email, copy the invitation link from the dialog and pass it on. Invitations expire after seven days, and inviting the same address again replaces the earlier one.-- Anyone can leave a workspace, except its last admin: make someone else an admin first.-- Admins can delete a workspace once it holds no documents. Deleted documents are kept for a while before they are gone for good, and the workspace can be deleted after that.+- **Members** lists who is in the workspace and when each person joined. Admins invite people by email as an admin, editor, or viewer, change roles, and remove people. Editors and admins change documents; viewers only look.+- **Invited**, for admins, lists invitations nobody has accepted yet, with who sent each one and when it expires. An invitation arrives by email; if the server doesn't send email, copy the invitation link from the dialog and pass it on. Invitations expire after seven days. **Resend** sends one again with a new link, and the earlier link stops working; so does inviting the same address again.+- **Settings** renames the workspace, and holds leaving and deleting it. Anyone can leave a workspace, except its last admin: make someone else an admin first. Admins can delete a workspace once it holds no documents. Deleted documents are kept for a while before they are gone for good, and the workspace can be deleted after that.Opening a workspace invitation works like a document invitation: sign in with the invited address, choose **Join workspace**, and Home shows the workspace.@@ -56,10 +65,10 @@ A Cloud document saves as you work, and the tab's dot shows edits that haven't r| State | What it means || ------------------------- | ----------------------------------------------------------------------------------------------------------------------------- |-| **Saved on this device** | You are offline. Your changes are kept here and upload once you are back online. |+| **Saved on this device** | You are offline. Your changes are kept here and upload once you are back online. || **Changed in two places** | Someone saved a newer version while you had changes the server didn't have. || **Couldn't save** | The server refused the upload. Your changes are safe on this device; **Try again**, or sign in again if your sign-in expired. |-| **View only** | You can look, select, copy, and follow others; the document can't be edited, so only Move and Hand are in the toolbar. |+| **View only** | You can look, select, copy, and follow others; the document can't be edited, so only Move and Hand are in the toolbar. |## When a Document Changed in Two Placesdiff --git a/packages/vue/src/i18n/locales/de/cloud/editor.json b/packages/vue/src/i18n/locales/de/cloud/editor.jsonindex 4a6a56750..f1fe9dbbb 100644--- a/packages/vue/src/i18n/locales/de/cloud/editor.json+++ b/packages/vue/src/i18n/locales/de/cloud/editor.json@@ -259,6 +259,22 @@"removeMember": "{name} entfernen","pendingInvitations": "Wartet auf Beitritt","revokeInvitation": "Zurückziehen",+ "membersSections": "Arbeitsbereich",+ "membersTab": "Mitglieder",+ "invitedTab": "Eingeladen",+ "settingsTab": "Einstellungen",+ "searchMembers": "Mitglieder suchen…",+ "noMembersMatch": "Niemand passt zu dieser Suche.",+ "memberJoined": "Beigetreten am {date}",+ "invitationSent": "Eingeladen am {date}",+ "invitationSentBy": "Eingeladen am {date} von {name}",+ "resendInvitation": "Erneut senden",+ "invitationResent": "Erneut gesendet",+ "noInvitations": "Niemand wartet auf den Beitritt",+ "noInvitationsDescription": "Eingeladene Personen erscheinen hier, bis sie annehmen.",+ "roleAdminDescription": "Lädt Personen ein, ändert Rollen und benennt den Arbeitsbereich um oder löscht ihn",+ "roleEditorDescription": "Erstellt und bearbeitet die Dokumente des Arbeitsbereichs",+ "roleViewerDescription": "Öffnet die Dokumente des Arbeitsbereichs, ohne sie zu ändern","leaveWorkspace": "Arbeitsbereich verlassen","workspaceAlreadyMember": "Diese Person ist bereits in diesem Arbeitsbereich.","workspaceLastAdmin": "Ein Arbeitsbereich braucht einen Admin. Mach zuerst jemand anderen zum Admin.",diff --git a/packages/vue/src/i18n/locales/de/cloud/portal.json b/packages/vue/src/i18n/locales/de/cloud/portal.jsonindex f674989fe..96e50426a 100644--- a/packages/vue/src/i18n/locales/de/cloud/portal.json+++ b/packages/vue/src/i18n/locales/de/cloud/portal.json@@ -91,8 +91,12 @@"accountSettings": "Kontoeinstellungen","sectionAccount": "Dein Konto","sectionServer": "Server",+ "profile": "Profil",+ "profileDescription": "Wie du für Personen auf {host} erscheinst.","security": "Anmeldung und Sicherheit","securityDescription": "Wie du dich bei {host} anmeldest.",+ "sessions": "Sitzungen",+ "sessionsDescription": "Wo dein Konto angemeldet ist und wann es angemeldet war.","overview": "Übersicht","accessRequests": "Zugangsanfragen","accessRequestsDescription": "Personen, die beitreten möchten. Nach der Genehmigung können sie sich anmelden; in jedem Fall erhalten sie eine E-Mail.",@@ -105,6 +109,49 @@"emailDeliveryDescription": "Einladungen, Anmeldelinks und Zugangsentscheidungen, die der Server versendet.","activity": "Aktivität","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",+ "save": "Speichern",+ "nameSaved": "Name gespeichert",+ "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.",+ "newEmail": "Neue E-Mail-Adresse",+ "sendConfirmation": "Link senden",+ "emailChangeSent": "Wir haben einen Link an {email} gesendet. Deine E-Mail-Adresse ändert sich, sobald du ihn öffnest.",+ "emailChanged": "Deine E-Mail-Adresse lautet jetzt {email}.",+ "emailChangeUnavailable": "Dieser Server versendet keine E-Mails, daher kannst du deine E-Mail-Adresse hier nicht ändern.",+ "accountId": "Konto-ID",+ "accountIdDescription": "Gib sie einem Administrator, wenn du Hilfe mit deinem Konto brauchst.",+ "memberSince": "Mitglied seit {date}",+ "activeSessions": "Angemeldete Sitzungen",+ "activeSessionsDescription": "Melde jede Sitzung ab, die du nicht kennst; sie endet sofort.",+ "signOutOtherSessions": "Andere Sitzungen abmelden",+ "signOutOtherSessionsHeading": "Alle anderen Sitzungen abmelden?",+ "signOutOtherSessionsDescription": "Jeder Browser und jede App, die bei deinem Konto angemeldet ist, muss sich erneut anmelden – außer dieser hier.",+ "thisSession": "Diese Sitzung",+ "desktopApp": "OpenPencil-App",+ "unknownBrowser": "Unbekannter Browser",+ "browserOn": "{browser} unter {system}",+ "lastActive": "Aktiv {when}",+ "signedInOn": "Angemeldet am {date}",+ "endSessionHeading": "{device} abmelden?",+ "endSessionDescription": "Wer diese Sitzung nutzt, muss sich erneut anmelden.",+ "recentSignIns": "Letzte Anmeldungen",+ "recentSignInsDescription": "Jede Anmeldung bei deinem Konto. Wenn eine nicht von dir war, ändere dein Passwort und melde diese Sitzung ab.",+ "noSignIns": "Noch keine Anmeldungen erfasst.",+ "signedInWith": "Mit {method}",+ "methodPassword": "Passwort",+ "methodGoogle": "Google",+ "methodApple": "Apple",+ "methodPasskey": "einem Passkey",+ "methodTwoStep": "zweistufiger Anmeldung",+ "methodEmailLink": "einem E-Mail-Link",+ "methodDesktop": "der OpenPencil-App",+ "methodOther": "einem anderen Anbieter","waysToSignIn": "Anmeldemethoden","waysToSignInDescription": "Behalte mindestens eine, damit du jederzeit wieder hineinkommst.","providerGoogle": "Google",@@ -113,6 +160,8 @@"notLinked": "Nicht verknüpft","link": "Verknüpfen","unlink": "Trennen",+ "unlinkHeading": "{provider} trennen?",+ "unlinkDescription": "Du kannst dich damit erst wieder anmelden, wenn du es erneut verknüpfst.","passwordSet": "Mit E-Mail-Adresse und Passwort anmelden","passwordNotSet": "Füge ein Passwort hinzu, um dich auch mit deiner E-Mail-Adresse anzumelden","change": "Ändern",@@ -131,6 +180,8 @@"passkeyAdded": "Hinzugefügt am {date}","unnamedPasskey": "Passkey","remove": "Entfernen",+ "removePasskeyHeading": "{name} entfernen?",+ "removePasskeyDescription": "Die Bildschirmsperre dieses Geräts meldet dich dann nicht mehr an.","noPasskeys": "Noch keine Passkeys.","adminTwoStepTitle": "Zweiten Anmeldeschritt aktivieren","adminTwoStepDescription": "Auf diesem Server müssen Administratoren eine Authenticator-App oder einen Passkey verwenden, bevor sie die Konsole öffnen.",@@ -139,7 +190,10 @@"authenticatorSetupKey": "Scannen nicht möglich? Gib diesen Schlüssel ein","recoveryCodesTitle": "Wiederherstellungscodes speichern","recoveryCodesDescription": "Mit jedem Code kannst du dich einmal anmelden, falls du deinen Authenticator verlierst. Bewahre sie sicher auf; sie werden nicht noch einmal angezeigt.",+ "copy": "Kopieren","copyCodes": "Codes kopieren",+ "downloadCodes": "Herunterladen",+ "recoveryCodesSaveFirst": "Kopiere die Codes oder lade sie herunter, bevor du fortfährst.","copyKey": "Schlüssel kopieren","copied": "Kopiert","done": "Fertig",@@ -159,10 +213,72 @@"reviewedBy": "{decision} von {name}","decline": "Ablehnen","removeAccess": "Zugang entziehen",+ "declineHeading": "{name} ablehnen?",+ "declineDescription": "Die Person erhält eine E-Mail darüber und kann später erneut anfragen.",+ "removeAccessHeading": "Zugang für {name} entziehen?",+ "removeAccessDescription": "Die Person kann sich nicht mehr anmelden und erhält eine E-Mail darüber.",+ "reviewNote": "Notiz für Administratoren (optional)",+ "noteDetail": "Notiz: {note}","noOneWaiting": "Niemand wartet","nothingHere": "Noch nichts vorhanden","requestsEmptyDescription": "Neue Anfragen erscheinen hier, und Administratoren erhalten für jede eine E-Mail.","searchPeople": "Personen suchen…",+ "filterEveryone": "Alle",+ "filterAdministrators": "Administratoren",+ "filterSuspended": "Gesperrt",+ "filterWithoutTwoStep": "Ohne zweistufige Anmeldung",+ "twoStepOff": "Ohne zweistufige Anmeldung",+ "notSignedIn": "Nicht angemeldet",+ "workspaceCount": {+ "one": "{count} Arbeitsbereich",+ "many": "{count} Arbeitsbereiche"+ },+ "pageRange": "{from}–{to} von {total}",+ "previousPage": "Vorherige Seite",+ "nextPage": "Nächste Seite",+ "noPeopleFound": "Keine Treffer",+ "noPeopleFoundDescription": "Versuche einen anderen Namen, eine andere E-Mail-Adresse oder einen anderen Filter.",+ "suspendedReason": "Gesperrt: {reason}",+ "suspendHeading": "{name} sperren?",+ "suspendDescription": "Die Person wird überall abgemeldet und kann sich erst wieder anmelden, wenn du das Konto entsperrst. Ihre Dateien bleiben erhalten.",+ "suspendReason": "Grund (optional)",+ "restoreHeading": "{name} entsperren?",+ "restoreDescription": "Die Person kann sich wieder anmelden.",+ "makeAdministratorHeading": "{name} zum Administrator machen?",+ "makeAdministratorDescription": "Administratoren genehmigen Konten, sperren Personen und öffnen diese Konsole.",+ "removeAdministratorHeading": "{name} die Administratorrechte entziehen?",+ "removeAdministratorDescription": "Konto und Dateien bleiben erhalten, aber diese Konsole kann die Person nicht mehr öffnen.",+ "signOutEverywhereHeading": "{name} überall abmelden?",+ "signOutEverywhereDescription": "Alle Sitzungen der Person enden sofort. Sie kann sich erneut anmelden.",+ "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.",+ "backToPeople": "Alle Personen",+ "personAccount": "Konto",+ "emailVerified": "Bestätigt",+ "emailNotVerified": "Nicht bestätigt",+ "joinedRow": "Beigetreten",+ "lastActiveRow": "Zuletzt aktiv",+ "signInMethods": "Anmeldemethoden",+ "twoStepRow": "Zweistufige Anmeldung",+ "twoStepNone": "Nicht eingerichtet",+ "passkeyCount": {+ "one": "{count} Passkey",+ "many": "{count} Passkeys"+ },+ "personWorkspaces": "Arbeitsbereiche",+ "personWorkspacesEmpty": "In keinem Arbeitsbereich.",+ "workspaceMembers": {+ "one": "{count} Mitglied",+ "many": "{count} Mitglieder"+ },+ "workspaceRoleAdmin": "Administrator",+ "workspaceRoleEditor": "Bearbeiter",+ "workspaceRoleViewer": "Betrachter",+ "personSessions": "Sitzungen",+ "noSessions": "Nirgends angemeldet.",+ "personNotFound": "Dieses Konto gibt es nicht",+ "personNotFoundDescription": "Es wurde möglicherweise entfernt. Kehre zur Personenliste zurück.","you": "(du)","administrator": "Administrator","suspended": "Gesperrt",@@ -196,6 +312,11 @@"emailAllSent": "Alles wurde gesendet","review": "Prüfen","open": "Öffnen",+ "usageSection": "Nutzung",+ "accounts": "Konten",+ "workspaces": "Arbeitsbereiche",+ "documents": "Dokumente",+ "storedFiles": "Gespeicherte Dateien","serverSection": "Server","serverSectionDescription": "Festgelegt in der Konfigurationsdatei des Servers.","deployment": "Bereitstellung",@@ -211,6 +332,10 @@"someoneElse": "Jemand","emailSuppressed": "Nicht gesendet","emailKindInvitation": "Einladung zu einem Dokument",+ "emailKindWorkspaceInvitation": "Einladung zu einem Arbeitsbereich",+ "emailKindEmailChangeRequested": "Änderung der E-Mail-Adresse angefordert",+ "emailKindNewSignIn": "Neue Anmeldung",+ "emailKindTwoStepChanged": "Zweistufige Anmeldung geändert","emailKindEnrollmentRequested": "Zugangsanfrage erhalten","emailKindAdminNotification": "Neue Zugangsanfrage (Administratoren)","emailKindEnrollmentApproved": "Zugang genehmigt",@@ -229,6 +354,8 @@"activityMadeAdmin": "ernannte zum Administrator:","activityRemovedAdmin": "entzog die Administratorrechte von","activityEmailRetried": "sendete eine E-Mail erneut an",+ "activityTwoStepReset": "setzte die zweistufige Anmeldung zurück für",+ "activityReason": "Grund: {reason}","activityChanged": "änderte","errorTitle": "Das hat nicht funktioniert","errorLastMethod": "Behalte mindestens eine Anmeldemethode.",@@ -239,6 +366,8 @@"errorNotAllowed": "Dazu bist du nicht berechtigt.","errorNetwork": "Der Server ist nicht erreichbar. Prüfe deine Verbindung.","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.","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/editor.json b/packages/vue/src/i18n/locales/es/cloud/editor.jsonindex 108cf55a2..1ac45f6df 100644--- a/packages/vue/src/i18n/locales/es/cloud/editor.json+++ b/packages/vue/src/i18n/locales/es/cloud/editor.json@@ -259,6 +259,22 @@"removeMember": "Quitar a {name}","pendingInvitations": "Pendientes de unirse","revokeInvitation": "Retirar",+ "membersSections": "Espacio de trabajo",+ "membersTab": "Miembros",+ "invitedTab": "Invitados",+ "settingsTab": "Ajustes",+ "searchMembers": "Buscar miembros…",+ "noMembersMatch": "Nadie coincide con esa búsqueda.",+ "memberJoined": "Se unió el {date}",+ "invitationSent": "Invitado el {date}",+ "invitationSentBy": "Invitado el {date} por {name}",+ "resendInvitation": "Reenviar",+ "invitationResent": "Enviada de nuevo",+ "noInvitations": "No hay nadie pendiente de unirse",+ "noInvitationsDescription": "Las personas que invites aparecen aquí hasta que acepten.",+ "roleAdminDescription": "Invita a personas, cambia roles y renombra o elimina el espacio de trabajo",+ "roleEditorDescription": "Crea y edita los documentos del espacio de trabajo",+ "roleViewerDescription": "Abre los documentos del espacio de trabajo sin cambiarlos","leaveWorkspace": "Salir del espacio","workspaceAlreadyMember": "Ya está en este espacio de trabajo.","workspaceLastAdmin": "Un espacio necesita un administrador. Haz administrador a otra persona primero.",diff --git a/packages/vue/src/i18n/locales/es/cloud/portal.json b/packages/vue/src/i18n/locales/es/cloud/portal.jsonindex 5bfae283c..0efb396b8 100644--- a/packages/vue/src/i18n/locales/es/cloud/portal.json+++ b/packages/vue/src/i18n/locales/es/cloud/portal.json@@ -91,8 +91,12 @@"accountSettings": "Ajustes de la cuenta","sectionAccount": "Tu cuenta","sectionServer": "Servidor",+ "profile": "Perfil",+ "profileDescription": "Cómo te ven las personas en {host}.","security": "Inicio de sesión y seguridad","securityDescription": "Cómo inicias sesión en {host}.",+ "sessions": "Sesiones",+ "sessionsDescription": "Dónde está iniciada tu cuenta y desde cuándo.","overview": "Resumen","accessRequests": "Solicitudes de acceso","accessRequestsDescription": "Personas que piden unirse. Al aprobarlas podrán iniciar sesión; en ambos casos reciben un correo.",@@ -105,6 +109,49 @@"emailDeliveryDescription": "Invitaciones, enlaces de inicio de sesión y decisiones de acceso que envía el servidor.","activity": "Actividad","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",+ "save": "Guardar",+ "nameSaved": "Nombre guardado",+ "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.",+ "newEmail": "Correo nuevo",+ "sendConfirmation": "Enviar enlace",+ "emailChangeSent": "Hemos enviado un enlace a {email}. Tu correo cambiará cuando lo abras.",+ "emailChanged": "Tu correo ahora es {email}.",+ "emailChangeUnavailable": "Este servidor no envía correos, así que aquí no puedes cambiar tu correo.",+ "accountId": "ID de la cuenta",+ "accountIdDescription": "Dáselo a un administrador cuando pidas ayuda con tu cuenta.",+ "memberSince": "Miembro desde el {date}",+ "activeSessions": "Sesiones iniciadas",+ "activeSessionsDescription": "Cierra cualquier sesión que no reconozcas; termina al instante.",+ "signOutOtherSessions": "Cerrar las demás sesiones",+ "signOutOtherSessionsHeading": "¿Cerrar todas las demás sesiones?",+ "signOutOtherSessionsDescription": "Todos los navegadores y apps con tu cuenta iniciada, salvo este, tendrán que volver a iniciar sesión.",+ "thisSession": "Esta sesión",+ "desktopApp": "App de OpenPencil",+ "unknownBrowser": "Navegador desconocido",+ "browserOn": "{browser} en {system}",+ "lastActive": "Activa {when}",+ "signedInOn": "Iniciada el {date}",+ "endSessionHeading": "¿Cerrar la sesión en {device}?",+ "endSessionDescription": "Quien use esa sesión tendrá que volver a iniciar sesión.",+ "recentSignIns": "Inicios de sesión recientes",+ "recentSignInsDescription": "Cada vez que se inició sesión en tu cuenta. Si alguno no fuiste tú, cambia tu contraseña y cierra esa sesión.",+ "noSignIns": "Aún no hay inicios de sesión registrados.",+ "signedInWith": "Con {method}",+ "methodPassword": "contraseña",+ "methodGoogle": "Google",+ "methodApple": "Apple",+ "methodPasskey": "una llave de acceso",+ "methodTwoStep": "verificación en dos pasos",+ "methodEmailLink": "un enlace por correo",+ "methodDesktop": "la app de OpenPencil",+ "methodOther": "otro proveedor","waysToSignIn": "Formas de iniciar sesión","waysToSignInDescription": "Conserva al menos una para poder volver a entrar siempre.","providerGoogle": "Google",@@ -113,6 +160,8 @@"notLinked": "Sin vincular","link": "Vincular","unlink": "Desvincular",+ "unlinkHeading": "¿Desvincular {provider}?",+ "unlinkDescription": "No podrás volver a iniciar sesión con esta cuenta hasta que la vincules.","passwordSet": "Inicia sesión con tu correo y contraseña","passwordNotSet": "Añade una contraseña para iniciar sesión también con tu correo","change": "Cambiar",@@ -131,6 +180,8 @@"passkeyAdded": "Añadida el {date}","unnamedPasskey": "Llave de acceso","remove": "Eliminar",+ "removePasskeyHeading": "¿Eliminar {name}?",+ "removePasskeyDescription": "El bloqueo de pantalla de ese dispositivo dejará de iniciar tu sesión.","noPasskeys": "Aún no hay llaves de acceso.","adminTwoStepTitle": "Activa un segundo paso de inicio de sesión","adminTwoStepDescription": "Este servidor exige que los administradores usen una app de autenticación o una llave de acceso antes de abrir la consola.",@@ -139,7 +190,10 @@"authenticatorSetupKey": "¿No puedes escanearlo? Introduce esta clave","recoveryCodesTitle": "Guarda tus códigos de recuperación","recoveryCodesDescription": "Cada código te permite iniciar sesión una vez si pierdes tu app de autenticación. Guárdalos en un lugar seguro; no se volverán a mostrar.",+ "copy": "Copiar","copyCodes": "Copiar códigos",+ "downloadCodes": "Descargar",+ "recoveryCodesSaveFirst": "Copia o descarga los códigos antes de continuar.","copyKey": "Copiar clave","copied": "Copiado","done": "Hecho",@@ -159,10 +213,72 @@"reviewedBy": "{decision} por {name}","decline": "Rechazar","removeAccess": "Retirar acceso",+ "declineHeading": "¿Rechazar a {name}?",+ "declineDescription": "Recibirá un correo avisándole y podrá volver a solicitarlo más adelante.",+ "removeAccessHeading": "¿Retirar el acceso a {name}?",+ "removeAccessDescription": "Ya no podrá iniciar sesión y recibirá un correo avisándole.",+ "reviewNote": "Nota para los administradores (opcional)",+ "noteDetail": "Nota: {note}","noOneWaiting": "No hay nadie en espera","nothingHere": "Aún no hay nada","requestsEmptyDescription": "Las nuevas solicitudes aparecen aquí y los administradores reciben un correo por cada una.","searchPeople": "Buscar personas…",+ "filterEveryone": "Todos",+ "filterAdministrators": "Administradores",+ "filterSuspended": "Suspendidas",+ "filterWithoutTwoStep": "Sin dos pasos",+ "twoStepOff": "Sin dos pasos",+ "notSignedIn": "Sin sesión iniciada",+ "workspaceCount": {+ "one": "{count} espacio de trabajo",+ "many": "{count} espacios de trabajo"+ },+ "pageRange": "{from}–{to} de {total}",+ "previousPage": "Página anterior",+ "nextPage": "Página siguiente",+ "noPeopleFound": "Nadie coincide",+ "noPeopleFoundDescription": "Prueba con otro nombre o correo, o con otro filtro.",+ "suspendedReason": "Suspendida: {reason}",+ "suspendHeading": "¿Suspender a {name}?",+ "suspendDescription": "Se cerrarán todas sus sesiones y no podrá iniciar sesión hasta que restaures la cuenta. Sus archivos se conservan.",+ "suspendReason": "Motivo (opcional)",+ "restoreHeading": "¿Restaurar a {name}?",+ "restoreDescription": "Podrá volver a iniciar sesión.",+ "makeAdministratorHeading": "¿Hacer administrador a {name}?",+ "makeAdministratorDescription": "Los administradores aprueban cuentas, suspenden a personas y abren esta consola.",+ "removeAdministratorHeading": "¿Quitar los permisos de administrador a {name}?",+ "removeAdministratorDescription": "Conserva su cuenta y sus archivos, pero no podrá abrir esta consola.",+ "signOutEverywhereHeading": "¿Cerrar todas las sesiones de {name}?",+ "signOutEverywhereDescription": "Todas sus sesiones terminan al instante. Podrá volver a iniciar sesión.",+ "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.",+ "backToPeople": "Todas las personas",+ "personAccount": "Cuenta",+ "emailVerified": "Verificado",+ "emailNotVerified": "Sin verificar",+ "joinedRow": "Se unió",+ "lastActiveRow": "Última actividad",+ "signInMethods": "Formas de iniciar sesión",+ "twoStepRow": "Verificación en dos pasos",+ "twoStepNone": "Sin configurar",+ "passkeyCount": {+ "one": "{count} llave de acceso",+ "many": "{count} llaves de acceso"+ },+ "personWorkspaces": "Espacios de trabajo",+ "personWorkspacesEmpty": "No está en ningún espacio de trabajo.",+ "workspaceMembers": {+ "one": "{count} miembro",+ "many": "{count} miembros"+ },+ "workspaceRoleAdmin": "Administrador",+ "workspaceRoleEditor": "Editor",+ "workspaceRoleViewer": "Lector",+ "personSessions": "Sesiones",+ "noSessions": "No tiene ninguna sesión iniciada.",+ "personNotFound": "Esta cuenta no existe",+ "personNotFoundDescription": "Puede que se haya eliminado. Vuelve a la lista de personas.","you": "(tú)","administrator": "Administrador","suspended": "Suspendida",@@ -196,6 +312,11 @@"emailAllSent": "Todo se ha enviado","review": "Revisar","open": "Abrir",+ "usageSection": "Uso",+ "accounts": "Cuentas",+ "workspaces": "Espacios de trabajo",+ "documents": "Documentos",+ "storedFiles": "Archivos guardados","serverSection": "Servidor","serverSectionDescription": "Se define en el archivo de configuración del servidor.","deployment": "Implementación",@@ -211,6 +332,10 @@"someoneElse": "Alguien","emailSuppressed": "No enviado","emailKindInvitation": "Invitación a un documento",+ "emailKindWorkspaceInvitation": "Invitación a un espacio de trabajo",+ "emailKindEmailChangeRequested": "Solicitud de cambio de correo",+ "emailKindNewSignIn": "Nuevo inicio de sesión",+ "emailKindTwoStepChanged": "Verificación en dos pasos modificada","emailKindEnrollmentRequested": "Solicitud de acceso recibida","emailKindAdminNotification": "Nueva solicitud de acceso (administradores)","emailKindEnrollmentApproved": "Acceso aprobado",@@ -229,6 +354,8 @@"activityMadeAdmin": "hizo administrador a","activityRemovedAdmin": "quitó los permisos de administrador a","activityEmailRetried": "reintentó un correo a",+ "activityTwoStepReset": "restableció la verificación en dos pasos de",+ "activityReason": "Motivo: {reason}","activityChanged": "cambió","errorTitle": "No ha funcionado","errorLastMethod": "Conserva al menos una forma de iniciar sesión.",@@ -239,6 +366,8 @@"errorNotAllowed": "No tienes permiso para hacer eso.","errorNetwork": "No se pudo conectar con el servidor. Comprueba tu conexión.","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.","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/editor.json b/packages/vue/src/i18n/locales/fr/cloud/editor.jsonindex 6b5bf3dd4..afef87e49 100644--- a/packages/vue/src/i18n/locales/fr/cloud/editor.json+++ b/packages/vue/src/i18n/locales/fr/cloud/editor.json@@ -259,6 +259,22 @@"removeMember": "Retirer {name}","pendingInvitations": "En attente","revokeInvitation": "Retirer",+ "membersSections": "Espace de travail",+ "membersTab": "Membres",+ "invitedTab": "Invités",+ "settingsTab": "Paramètres",+ "searchMembers": "Rechercher des membres…",+ "noMembersMatch": "Aucun membre ne correspond à cette recherche.",+ "memberJoined": "A rejoint le {date}",+ "invitationSent": "Invité le {date}",+ "invitationSentBy": "Invité le {date} par {name}",+ "resendInvitation": "Renvoyer",+ "invitationResent": "Renvoyée",+ "noInvitations": "Personne n’attend de rejoindre l’espace",+ "noInvitationsDescription": "Les personnes que vous invitez apparaissent ici jusqu’à ce qu’elles acceptent.",+ "roleAdminDescription": "Invite des personnes, modifie les rôles, et renomme ou supprime l’espace de travail",+ "roleEditorDescription": "Crée et modifie les documents de l’espace de travail",+ "roleViewerDescription": "Ouvre les documents de l’espace de travail sans les modifier","leaveWorkspace": "Quitter l’espace","workspaceAlreadyMember": "Cette personne fait déjà partie de l’espace.","workspaceLastAdmin": "Un espace a besoin d’un admin. Nommez d’abord quelqu’un d’autre admin.",diff --git a/packages/vue/src/i18n/locales/fr/cloud/portal.json b/packages/vue/src/i18n/locales/fr/cloud/portal.jsonindex e486e64e8..18c1b10e9 100644--- a/packages/vue/src/i18n/locales/fr/cloud/portal.json+++ b/packages/vue/src/i18n/locales/fr/cloud/portal.json@@ -91,8 +91,12 @@"accountSettings": "Paramètres du compte","sectionAccount": "Votre compte","sectionServer": "Serveur",+ "profile": "Profil",+ "profileDescription": "Comment les personnes de {host} vous voient.","security": "Connexion et sécurité","securityDescription": "Comment vous vous connectez à {host}.",+ "sessions": "Sessions",+ "sessionsDescription": "Où votre compte est connecté, et depuis quand.","overview": "Vue d’ensemble","accessRequests": "Demandes d’accès","accessRequestsDescription": "Personnes qui demandent à rejoindre le serveur. Une approbation leur permet de se connecter ; chacune reçoit un e-mail dans tous les cas.",@@ -105,6 +109,49 @@"emailDeliveryDescription": "Invitations, liens de connexion et décisions d’accès envoyés par le serveur.","activity": "Activité","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",+ "save": "Enregistrer",+ "nameSaved": "Nom enregistré",+ "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.",+ "newEmail": "Nouvelle adresse e-mail",+ "sendConfirmation": "Envoyer le lien",+ "emailChangeSent": "Nous avons envoyé un lien à {email}. Votre adresse changera une fois le lien suivi.",+ "emailChanged": "Votre adresse e-mail est désormais {email}.",+ "emailChangeUnavailable": "Ce serveur n’envoie pas d’e-mails ; vous ne pouvez donc pas modifier votre adresse ici.",+ "accountId": "ID du compte",+ "accountIdDescription": "Communiquez-le à un administrateur lorsque vous demandez de l’aide pour votre compte.",+ "memberSince": "Membre depuis le {date}",+ "activeSessions": "Sessions connectées",+ "activeSessionsDescription": "Déconnectez toute session que vous ne reconnaissez pas ; elle prend fin immédiatement.",+ "signOutOtherSessions": "Déconnecter les autres sessions",+ "signOutOtherSessionsHeading": "Déconnecter toutes les autres sessions ?",+ "signOutOtherSessionsDescription": "Tous les navigateurs et apps connectés à votre compte, sauf celui-ci, devront se reconnecter.",+ "thisSession": "Cette session",+ "desktopApp": "App OpenPencil",+ "unknownBrowser": "Navigateur inconnu",+ "browserOn": "{browser} sur {system}",+ "lastActive": "Dernière activité {when}",+ "signedInOn": "Connectée le {date}",+ "endSessionHeading": "Déconnecter {device} ?",+ "endSessionDescription": "La personne qui utilise cette session devra se reconnecter.",+ "recentSignIns": "Connexions récentes",+ "recentSignInsDescription": "Chaque connexion à votre compte. Si l’une d’elles ne vient pas de vous, changez votre mot de passe et déconnectez cette session.",+ "noSignIns": "Aucune connexion enregistrée pour le moment.",+ "signedInWith": "Avec {method}",+ "methodPassword": "un mot de passe",+ "methodGoogle": "un compte Google",+ "methodApple": "un compte Apple",+ "methodPasskey": "une clé d’accès",+ "methodTwoStep": "la connexion en deux étapes",+ "methodEmailLink": "un lien par e-mail",+ "methodDesktop": "l’app OpenPencil",+ "methodOther": "un autre fournisseur","waysToSignIn": "Moyens de connexion","waysToSignInDescription": "Conservez-en au moins un pour toujours pouvoir revenir.","providerGoogle": "Google",@@ -113,6 +160,8 @@"notLinked": "Non associé","link": "Associer","unlink": "Dissocier",+ "unlinkHeading": "Dissocier {provider} ?",+ "unlinkDescription": "Vous ne pourrez plus vous connecter avec ce compte tant que vous ne l’aurez pas associé à nouveau.","passwordSet": "Connectez-vous avec votre e-mail et votre mot de passe","passwordNotSet": "Ajoutez un mot de passe pour pouvoir aussi vous connecter avec votre e-mail","change": "Modifier",@@ -131,6 +180,8 @@"passkeyAdded": "Ajoutée le {date}","unnamedPasskey": "Clé d’accès","remove": "Supprimer",+ "removePasskeyHeading": "Supprimer {name} ?",+ "removePasskeyDescription": "Le verrouillage d’écran de cet appareil ne vous connectera plus.","noPasskeys": "Aucune clé d’accès pour le moment.","adminTwoStepTitle": "Activez une seconde étape de connexion","adminTwoStepDescription": "Ce serveur exige que les administrateurs utilisent une app d’authentification ou une clé d’accès avant d’ouvrir la console.",@@ -139,7 +190,10 @@"authenticatorSetupKey": "Impossible de scanner ? Saisissez cette clé","recoveryCodesTitle": "Enregistrez vos codes de récupération","recoveryCodesDescription": "Chaque code vous permet de vous connecter une fois si vous perdez votre app d’authentification. Conservez-les en lieu sûr ; ils ne seront plus affichés.",+ "copy": "Copier","copyCodes": "Copier les codes",+ "downloadCodes": "Télécharger",+ "recoveryCodesSaveFirst": "Copiez ou téléchargez les codes avant de continuer.","copyKey": "Copier la clé","copied": "Copié","done": "Terminé",@@ -159,10 +213,72 @@"reviewedBy": "{decision} par {name}","decline": "Refuser","removeAccess": "Retirer l’accès",+ "declineHeading": "Refuser {name} ?",+ "declineDescription": "Cette personne en est informée par e-mail et pourra refaire une demande plus tard.",+ "removeAccessHeading": "Retirer l’accès de {name} ?",+ "removeAccessDescription": "Cette personne ne pourra plus se connecter et en sera informée par e-mail.",+ "reviewNote": "Note pour les administrateurs (facultatif)",+ "noteDetail": "Note : {note}","noOneWaiting": "Personne n’attend","nothingHere": "Rien pour le moment","requestsEmptyDescription": "Les nouvelles demandes apparaissent ici, et les administrateurs reçoivent un e-mail pour chacune.","searchPeople": "Rechercher des personnes…",+ "filterEveryone": "Tout le monde",+ "filterAdministrators": "Administrateurs",+ "filterSuspended": "Suspendus",+ "filterWithoutTwoStep": "Sans deux étapes",+ "twoStepOff": "Sans deux étapes",+ "notSignedIn": "Non connecté",+ "workspaceCount": {+ "one": "{count} espace de travail",+ "many": "{count} espaces de travail"+ },+ "pageRange": "{from}–{to} sur {total}",+ "previousPage": "Page précédente",+ "nextPage": "Page suivante",+ "noPeopleFound": "Aucun résultat",+ "noPeopleFoundDescription": "Essayez un autre nom ou e-mail, ou un autre filtre.",+ "suspendedReason": "Suspendu : {reason}",+ "suspendHeading": "Suspendre {name} ?",+ "suspendDescription": "Cette personne est déconnectée partout et ne pourra plus se connecter tant que vous n’aurez pas rétabli le compte. Ses fichiers sont conservés.",+ "suspendReason": "Motif (facultatif)",+ "restoreHeading": "Rétablir {name} ?",+ "restoreDescription": "Cette personne pourra de nouveau se connecter.",+ "makeAdministratorHeading": "Nommer {name} administrateur ?",+ "makeAdministratorDescription": "Les administrateurs approuvent les comptes, suspendent des personnes et ouvrent cette console.",+ "removeAdministratorHeading": "Retirer les droits d’administrateur à {name} ?",+ "removeAdministratorDescription": "Cette personne conserve son compte et ses fichiers, mais ne peut plus ouvrir cette console.",+ "signOutEverywhereHeading": "Déconnecter {name} partout ?",+ "signOutEverywhereDescription": "Toutes ses sessions prennent fin immédiatement. Cette personne pourra se reconnecter.",+ "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.",+ "backToPeople": "Toutes les personnes",+ "personAccount": "Compte",+ "emailVerified": "Vérifiée",+ "emailNotVerified": "Non vérifiée",+ "joinedRow": "Inscription",+ "lastActiveRow": "Dernière activité",+ "signInMethods": "Moyens de connexion",+ "twoStepRow": "Connexion en deux étapes",+ "twoStepNone": "Non configurée",+ "passkeyCount": {+ "one": "{count} clé d’accès",+ "many": "{count} clés d’accès"+ },+ "personWorkspaces": "Espaces de travail",+ "personWorkspacesEmpty": "Membre d’aucun espace de travail.",+ "workspaceMembers": {+ "one": "{count} membre",+ "many": "{count} membres"+ },+ "workspaceRoleAdmin": "Administrateur",+ "workspaceRoleEditor": "Éditeur",+ "workspaceRoleViewer": "Lecteur",+ "personSessions": "Sessions",+ "noSessions": "Connecté nulle part.",+ "personNotFound": "Ce compte n’existe pas",+ "personNotFoundDescription": "Il a peut-être été supprimé. Revenez à la liste des personnes.","you": "(vous)","administrator": "Administrateur","suspended": "Suspendu",@@ -196,6 +312,11 @@"emailAllSent": "Tout a été envoyé","review": "Examiner","open": "Ouvrir",+ "usageSection": "Utilisation",+ "accounts": "Comptes",+ "workspaces": "Espaces de travail",+ "documents": "Documents",+ "storedFiles": "Fichiers stockés","serverSection": "Serveur","serverSectionDescription": "Défini dans le fichier de configuration du serveur.","deployment": "Déploiement",@@ -211,6 +332,10 @@"someoneElse": "Quelqu’un","emailSuppressed": "Non envoyé","emailKindInvitation": "Invitation à un document",+ "emailKindWorkspaceInvitation": "Invitation à un espace de travail",+ "emailKindEmailChangeRequested": "Demande de changement d’adresse e-mail",+ "emailKindNewSignIn": "Nouvelle connexion",+ "emailKindTwoStepChanged": "Connexion en deux étapes modifiée","emailKindEnrollmentRequested": "Demande d’accès reçue","emailKindAdminNotification": "Nouvelle demande d’accès (administrateurs)","emailKindEnrollmentApproved": "Accès approuvé",@@ -229,6 +354,8 @@"activityMadeAdmin": "a nommé administrateur :","activityRemovedAdmin": "a retiré les droits d’administrateur à","activityEmailRetried": "a renvoyé un e-mail à",+ "activityTwoStepReset": "a réinitialisé la connexion en deux étapes de",+ "activityReason": "Motif : {reason}","activityChanged": "a modifié","errorTitle": "Cela n’a pas fonctionné","errorLastMethod": "Conservez au moins un moyen de connexion.",@@ -239,6 +366,8 @@"errorNotAllowed": "Vous n’avez pas l’autorisation de faire cela.","errorNetwork": "Impossible de joindre le serveur. Vérifiez votre connexion.","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.","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/editor.json b/packages/vue/src/i18n/locales/it/cloud/editor.jsonindex 34ae6ad24..3cb4d5175 100644--- a/packages/vue/src/i18n/locales/it/cloud/editor.json+++ b/packages/vue/src/i18n/locales/it/cloud/editor.json@@ -259,6 +259,22 @@"removeMember": "Rimuovi {name}","pendingInvitations": "In attesa di entrare","revokeInvitation": "Ritira",+ "membersSections": "Area di lavoro",+ "membersTab": "Membri",+ "invitedTab": "Invitati",+ "settingsTab": "Impostazioni",+ "searchMembers": "Cerca membri…",+ "noMembersMatch": "Nessuno corrisponde alla ricerca.",+ "memberJoined": "Entrato il {date}",+ "invitationSent": "Invitato il {date}",+ "invitationSentBy": "Invitato il {date} da {name}",+ "resendInvitation": "Invia di nuovo",+ "invitationResent": "Inviato di nuovo",+ "noInvitations": "Nessuno in attesa di entrare",+ "noInvitationsDescription": "Le persone che inviti compaiono qui finché non accettano.",+ "roleAdminDescription": "Invita persone, cambia i ruoli e rinomina o elimina l’area di lavoro",+ "roleEditorDescription": "Crea e modifica i documenti dell’area di lavoro",+ "roleViewerDescription": "Apre i documenti dell’area di lavoro senza modificarli","leaveWorkspace": "Lascia l’area","workspaceAlreadyMember": "È già in quest’area di lavoro.","workspaceLastAdmin": "Un’area ha bisogno di un admin. Prima rendi admin qualcun altro.",diff --git a/packages/vue/src/i18n/locales/it/cloud/portal.json b/packages/vue/src/i18n/locales/it/cloud/portal.jsonindex a8a6598dd..7ab1e0b68 100644--- a/packages/vue/src/i18n/locales/it/cloud/portal.json+++ b/packages/vue/src/i18n/locales/it/cloud/portal.json@@ -91,8 +91,12 @@"accountSettings": "Impostazioni account","sectionAccount": "Il tuo account","sectionServer": "Server",+ "profile": "Profilo",+ "profileDescription": "Come ti vedono le persone su {host}.","security": "Accesso e sicurezza","securityDescription": "Come accedi a {host}.",+ "sessions": "Sessioni",+ "sessionsDescription": "Dove è stato effettuato l’accesso al tuo account, e quando.","overview": "Panoramica","accessRequests": "Richieste di accesso","accessRequestsDescription": "Persone che chiedono di unirsi. Approvandole potranno accedere; in ogni caso ricevono un’email.",@@ -105,6 +109,49 @@"emailDeliveryDescription": "Inviti, link di accesso e decisioni sull’accesso inviati dal server.","activity": "Attività","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",+ "save": "Salva",+ "nameSaved": "Nome salvato",+ "changeEmail": "Cambia email",+ "changeEmailTitle": "Cambia la tua email",+ "changeEmailDescription": "Inviamo un link al nuovo indirizzo. {email} resta la tua email finché non lo apri.",+ "newEmail": "Nuova email",+ "sendConfirmation": "Invia link",+ "emailChangeSent": "Abbiamo inviato un link a {email}. La tua email cambia quando lo apri.",+ "emailChanged": "La tua email ora è {email}.",+ "emailChangeUnavailable": "Questo server non invia email, quindi qui non puoi cambiare la tua email.",+ "accountId": "ID account",+ "accountIdDescription": "Comunicalo a un amministratore quando chiedi aiuto per il tuo account.",+ "memberSince": "Membro dal {date}",+ "activeSessions": "Sessioni con accesso attivo",+ "activeSessionsDescription": "Disconnetti qualsiasi sessione che non riconosci; termina subito.",+ "signOutOtherSessions": "Disconnetti le altre sessioni",+ "signOutOtherSessionsHeading": "Disconnettere tutte le altre sessioni?",+ "signOutOtherSessionsDescription": "Ogni browser e app collegati al tuo account, tranne questo, dovrà accedere di nuovo.",+ "thisSession": "Questa sessione",+ "desktopApp": "App OpenPencil",+ "unknownBrowser": "Browser sconosciuto",+ "browserOn": "{browser} su {system}",+ "lastActive": "Attiva {when}",+ "signedInOn": "Accesso il {date}",+ "endSessionHeading": "Disconnettere {device}?",+ "endSessionDescription": "Chi usa quella sessione dovrà accedere di nuovo.",+ "recentSignIns": "Accessi recenti",+ "recentSignInsDescription": "Ogni volta che è stato effettuato l’accesso al tuo account. Se uno non eri tu, cambia la password e disconnetti quella sessione.",+ "noSignIns": "Ancora nessun accesso registrato.",+ "signedInWith": "Con {method}",+ "methodPassword": "password",+ "methodGoogle": "Google",+ "methodApple": "Apple",+ "methodPasskey": "una passkey",+ "methodTwoStep": "la verifica in due passaggi",+ "methodEmailLink": "un link via email",+ "methodDesktop": "l’app OpenPencil",+ "methodOther": "un altro provider","waysToSignIn": "Metodi di accesso","waysToSignInDescription": "Mantienine almeno uno, così potrai sempre rientrare.","providerGoogle": "Google",@@ -113,6 +160,8 @@"notLinked": "Non collegato","link": "Collega","unlink": "Scollega",+ "unlinkHeading": "Scollegare {provider}?",+ "unlinkDescription": "Non potrai più accedere con questo metodo finché non lo ricolleghi.","passwordSet": "Accedi con email e password","passwordNotSet": "Aggiungi una password per accedere anche con la tua email","change": "Cambia",@@ -131,6 +180,8 @@"passkeyAdded": "Aggiunta il {date}","unnamedPasskey": "Passkey","remove": "Rimuovi",+ "removePasskeyHeading": "Rimuovere {name}?",+ "removePasskeyDescription": "Il blocco schermo di quel dispositivo non ti farà più accedere.","noPasskeys": "Ancora nessuna passkey.","adminTwoStepTitle": "Attiva un secondo passaggio di accesso","adminTwoStepDescription": "Questo server richiede agli amministratori di usare un’app di autenticazione o una passkey prima di aprire la console.",@@ -139,7 +190,10 @@"authenticatorSetupKey": "Non riesci a scansionare? Inserisci questa chiave","recoveryCodesTitle": "Salva i codici di recupero","recoveryCodesDescription": "Ogni codice ti permette di accedere una volta se perdi l’app di autenticazione. Conservali in un posto sicuro: non verranno più mostrati.",+ "copy": "Copia","copyCodes": "Copia codici",+ "downloadCodes": "Scarica",+ "recoveryCodesSaveFirst": "Copia o scarica i codici prima di continuare.","copyKey": "Copia chiave","copied": "Copiato","done": "Fatto",@@ -159,10 +213,72 @@"reviewedBy": "{decision} da {name}","decline": "Rifiuta","removeAccess": "Revoca accesso",+ "declineHeading": "Rifiutare {name}?",+ "declineDescription": "Riceve un’email che lo comunica e può richiedere di nuovo più tardi.",+ "removeAccessHeading": "Revocare l’accesso a {name}?",+ "removeAccessDescription": "Non potrà più accedere e riceverà un’email che lo comunica.",+ "reviewNote": "Nota per gli amministratori (facoltativa)",+ "noteDetail": "Nota: {note}","noOneWaiting": "Nessuno in attesa","nothingHere": "Ancora niente qui","requestsEmptyDescription": "Le nuove richieste compaiono qui e gli amministratori ricevono un’email per ciascuna.","searchPeople": "Cerca persone…",+ "filterEveryone": "Tutti",+ "filterAdministrators": "Amministratori",+ "filterSuspended": "Sospesi",+ "filterWithoutTwoStep": "Senza verifica in due passaggi",+ "twoStepOff": "Senza verifica in due passaggi",+ "notSignedIn": "Nessun accesso",+ "workspaceCount": {+ "one": "{count} area di lavoro",+ "many": "{count} aree di lavoro"+ },+ "pageRange": "{from}–{to} di {total}",+ "previousPage": "Pagina precedente",+ "nextPage": "Pagina successiva",+ "noPeopleFound": "Nessuna corrispondenza",+ "noPeopleFoundDescription": "Prova un altro nome o un’altra email, oppure un altro filtro.",+ "suspendedReason": "Sospeso: {reason}",+ "suspendHeading": "Sospendere {name}?",+ "suspendDescription": "Viene disconnesso ovunque e non può accedere finché non ripristini l’account. I suoi file restano.",+ "suspendReason": "Motivo (facoltativo)",+ "restoreHeading": "Ripristinare {name}?",+ "restoreDescription": "Potrà accedere di nuovo.",+ "makeAdministratorHeading": "Rendere {name} amministratore?",+ "makeAdministratorDescription": "Gli amministratori approvano gli account, sospendono le persone e aprono questa console.",+ "removeAdministratorHeading": "Rimuovere i diritti di amministratore a {name}?",+ "removeAdministratorDescription": "Mantiene account e file, ma non può aprire questa console.",+ "signOutEverywhereHeading": "Disconnettere {name} ovunque?",+ "signOutEverywhereDescription": "Tutte le sue sessioni terminano subito. Potrà accedere di nuovo.",+ "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.",+ "backToPeople": "Tutte le persone",+ "personAccount": "Account",+ "emailVerified": "Verificata",+ "emailNotVerified": "Non verificata",+ "joinedRow": "Iscrizione",+ "lastActiveRow": "Ultima attività",+ "signInMethods": "Metodi di accesso",+ "twoStepRow": "Verifica in due passaggi",+ "twoStepNone": "Non configurata",+ "passkeyCount": {+ "one": "{count} passkey",+ "many": "{count} passkey"+ },+ "personWorkspaces": "Aree di lavoro",+ "personWorkspacesEmpty": "Non è in nessuna area di lavoro.",+ "workspaceMembers": {+ "one": "{count} membro",+ "many": "{count} membri"+ },+ "workspaceRoleAdmin": "Amministratore",+ "workspaceRoleEditor": "Editor",+ "workspaceRoleViewer": "Visualizzatore",+ "personSessions": "Sessioni",+ "noSessions": "Nessun accesso attivo.",+ "personNotFound": "Questo account non esiste",+ "personNotFoundDescription": "Potrebbe essere stato rimosso. Torna all’elenco delle persone.","you": "(tu)","administrator": "Amministratore","suspended": "Sospeso",@@ -196,6 +312,11 @@"emailAllSent": "Tutto è stato inviato","review": "Esamina","open": "Apri",+ "usageSection": "Utilizzo",+ "accounts": "Account",+ "workspaces": "Aree di lavoro",+ "documents": "Documenti",+ "storedFiles": "File archiviati","serverSection": "Server","serverSectionDescription": "Impostato nel file di configurazione del server.","deployment": "Distribuzione",@@ -211,6 +332,10 @@"someoneElse": "Qualcuno","emailSuppressed": "Non inviata","emailKindInvitation": "Invito a un documento",+ "emailKindWorkspaceInvitation": "Invito a un’area di lavoro",+ "emailKindEmailChangeRequested": "Richiesta di cambio email",+ "emailKindNewSignIn": "Nuovo accesso",+ "emailKindTwoStepChanged": "Verifica in due passaggi modificata","emailKindEnrollmentRequested": "Richiesta di accesso ricevuta","emailKindAdminNotification": "Nuova richiesta di accesso (amministratori)","emailKindEnrollmentApproved": "Accesso approvato",@@ -229,6 +354,8 @@"activityMadeAdmin": "ha reso amministratore","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",+ "activityReason": "Motivo: {reason}","activityChanged": "ha modificato","errorTitle": "Operazione non riuscita","errorLastMethod": "Mantieni almeno un metodo di accesso.",@@ -239,6 +366,8 @@"errorNotAllowed": "Non hai l’autorizzazione per farlo.","errorNetwork": "Impossibile raggiungere il server. Controlla la connessione.","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.","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/editor.json b/packages/vue/src/i18n/locales/ja/cloud/editor.jsonindex a17237619..add46deea 100644--- a/packages/vue/src/i18n/locales/ja/cloud/editor.json+++ b/packages/vue/src/i18n/locales/ja/cloud/editor.json@@ -256,6 +256,22 @@"removeMember": "{name} を削除","pendingInvitations": "参加待ち","revokeInvitation": "取り消す",+ "membersSections": "ワークスペース",+ "membersTab": "メンバー",+ "invitedTab": "招待中",+ "settingsTab": "設定",+ "searchMembers": "メンバーを検索…",+ "noMembersMatch": "検索に一致するメンバーはいません。",+ "memberJoined": "{date}に参加",+ "invitationSent": "{date}に招待",+ "invitationSentBy": "{date}に {name} さんが招待",+ "resendInvitation": "再送信",+ "invitationResent": "再送信しました",+ "noInvitations": "参加待ちの人はいません",+ "noInvitationsDescription": "招待した人は、承諾するまでここに表示されます。",+ "roleAdminDescription": "メンバーの招待、役割の変更、ワークスペースの名前変更や削除ができます",+ "roleEditorDescription": "ワークスペースのドキュメントを作成・編集できます",+ "roleViewerDescription": "ワークスペースのドキュメントを変更せずに開けます","leaveWorkspace": "ワークスペースから退出","workspaceAlreadyMember": "すでにこのワークスペースのメンバーです。","workspaceLastAdmin": "ワークスペースには管理者が必要です。先に別のメンバーを管理者にしてください。",diff --git a/packages/vue/src/i18n/locales/ja/cloud/portal.json b/packages/vue/src/i18n/locales/ja/cloud/portal.jsonindex ee5ba89f5..da5effe95 100644--- a/packages/vue/src/i18n/locales/ja/cloud/portal.json+++ b/packages/vue/src/i18n/locales/ja/cloud/portal.json@@ -91,8 +91,12 @@"accountSettings": "アカウント設定","sectionAccount": "あなたのアカウント","sectionServer": "サーバー",+ "profile": "プロフィール",+ "profileDescription": "{host} でほかの人に表示されるあなたの情報です。","security": "サインインとセキュリティ","securityDescription": "{host} へのサインイン方法です。",+ "sessions": "セッション",+ "sessionsDescription": "あなたのアカウントがサインインしている場所と、その日時です。","overview": "概要","accessRequests": "アクセスリクエスト","accessRequestsDescription": "参加を希望している人です。承認するとサインインできるようになります。どちらの場合も本人にメールが届きます。",@@ -104,6 +108,49 @@"emailDeliveryDescription": "サーバーが送信する招待、サインイン用リンク、アクセスの審査結果です。","activity": "アクティビティ","activityDescription": "このサーバーで管理者が行った操作です。",+ "detailsSection": "詳細",+ "detailsSectionDescription": "あなたの名前と画像は、編集やコメントの横に表示されます。",+ "picture": "画像",+ "pictureFromProvider": "リンク済みアカウントの画像",+ "pictureInitials": "画像のあるアカウントをリンクするまでは、イニシャルを表示します",+ "save": "保存",+ "nameSaved": "名前を保存しました",+ "changeEmail": "メールアドレスを変更",+ "changeEmailTitle": "メールアドレスを変更",+ "changeEmailDescription": "新しいアドレスにリンクを送信します。リンクを開くまでは {email} がメールアドレスのままです。",+ "newEmail": "新しいメールアドレス",+ "sendConfirmation": "リンクを送信",+ "emailChangeSent": "{email} にリンクを送信しました。リンクを開くとメールアドレスが変更されます。",+ "emailChanged": "メールアドレスを {email} に変更しました。",+ "emailChangeUnavailable": "このサーバーはメールを送信しないため、ここではメールアドレスを変更できません。",+ "accountId": "アカウント ID",+ "accountIdDescription": "アカウントについて管理者に問い合わせるときに伝えてください。",+ "memberSince": "{date}から利用",+ "activeSessions": "サインイン中のセッション",+ "activeSessionsDescription": "心当たりのないセッションはサインアウトしてください。すぐに終了します。",+ "signOutOtherSessions": "ほかのセッションからサインアウト",+ "signOutOtherSessionsHeading": "ほかのすべてのセッションからサインアウトしますか?",+ "signOutOtherSessionsDescription": "このセッションを除き、あなたのアカウントでサインインしているすべてのブラウザーとアプリで、もう一度サインインが必要になります。",+ "thisSession": "このセッション",+ "desktopApp": "OpenPencil アプリ",+ "unknownBrowser": "不明なブラウザー",+ "browserOn": "{browser}({system})",+ "lastActive": "{when}にアクティブ",+ "signedInOn": "{date}にサインイン",+ "endSessionHeading": "{device} からサインアウトしますか?",+ "endSessionDescription": "そのセッションを使っている人は、もう一度サインインが必要になります。",+ "recentSignIns": "最近のサインイン",+ "recentSignInsDescription": "アカウントにサインインした記録です。心当たりのないものがあれば、パスワードを変更し、そのセッションをサインアウトしてください。",+ "noSignIns": "サインインの記録はまだありません。",+ "signedInWith": "{method}を使用",+ "methodPassword": "パスワード",+ "methodGoogle": "Google",+ "methodApple": "Apple",+ "methodPasskey": "パスキー",+ "methodTwoStep": "2段階認証",+ "methodEmailLink": "メールのリンク",+ "methodDesktop": "OpenPencil アプリ",+ "methodOther": "別のプロバイダー","waysToSignIn": "サインイン方法","waysToSignInDescription": "いつでもサインインできるよう、少なくとも1つは残してください。","providerGoogle": "Google",@@ -112,6 +159,8 @@"notLinked": "未リンク","link": "リンク","unlink": "リンクを解除",+ "unlinkHeading": "{provider} のリンクを解除しますか?",+ "unlinkDescription": "もう一度リンクするまで、この方法ではサインインできません。","passwordSet": "メールアドレスとパスワードでサインイン","passwordNotSet": "パスワードを追加すると、メールアドレスでもサインインできます","change": "変更",@@ -130,6 +179,8 @@"passkeyAdded": "{date}に追加","unnamedPasskey": "パスキー","remove": "削除",+ "removePasskeyHeading": "{name} を削除しますか?",+ "removePasskeyDescription": "そのデバイスの画面ロックではサインインできなくなります。","noPasskeys": "パスキーはまだありません。","adminTwoStepTitle": "2段階認証をオンにしてください","adminTwoStepDescription": "このサーバーでは、管理者がコンソールを開く前に認証アプリまたはパスキーを使う必要があります。",@@ -138,7 +189,10 @@"authenticatorSetupKey": "スキャンできない場合はこのキーを入力","recoveryCodesTitle": "リカバリーコードを保存してください","recoveryCodesDescription": "認証アプリを使えなくなった場合、各コードで1回サインインできます。安全な場所に保管してください。再表示はできません。",+ "copy": "コピー","copyCodes": "コードをコピー",+ "downloadCodes": "ダウンロード",+ "recoveryCodesSaveFirst": "続行する前に、コードをコピーするかダウンロードしてください。","copyKey": "キーをコピー","copied": "コピーしました","done": "完了",@@ -158,10 +212,69 @@"reviewedBy": "{decision}({name})","decline": "却下","removeAccess": "アクセスを削除",+ "declineHeading": "{name}を却下しますか?",+ "declineDescription": "本人にその旨のメールが届きます。後でもう一度リクエストできます。",+ "removeAccessHeading": "{name}のアクセスを削除しますか?",+ "removeAccessDescription": "サインインできなくなり、本人にその旨のメールが届きます。",+ "reviewNote": "管理者向けのメモ(任意)",+ "noteDetail": "メモ:{note}","noOneWaiting": "保留中のリクエストはありません","nothingHere": "まだ何もありません","requestsEmptyDescription": "新しいリクエストはここに表示され、そのたびに管理者にメールが届きます。","searchPeople": "ユーザーを検索…",+ "filterEveryone": "全員",+ "filterAdministrators": "管理者",+ "filterSuspended": "停止中",+ "filterWithoutTwoStep": "2段階認証なし",+ "twoStepOff": "2段階認証なし",+ "notSignedIn": "サインインしていません",+ "workspaceCount": {+ "many": "ワークスペース {count} 件"+ },+ "pageRange": "{from}–{to} / {total}",+ "previousPage": "前のページ",+ "nextPage": "次のページ",+ "noPeopleFound": "該当するユーザーはいません",+ "noPeopleFoundDescription": "別の名前やメールアドレス、または別のフィルターをお試しください。",+ "suspendedReason": "停止中:{reason}",+ "suspendHeading": "{name}を停止しますか?",+ "suspendDescription": "すべての場所からサインアウトされ、アカウントを復元するまでサインインできません。ファイルは残ります。",+ "suspendReason": "理由(任意)",+ "restoreHeading": "{name}を復元しますか?",+ "restoreDescription": "再びサインインできるようになります。",+ "makeAdministratorHeading": "{name}を管理者にしますか?",+ "makeAdministratorDescription": "管理者はアカウントの承認やユーザーの停止を行い、このコンソールを開けます。",+ "removeAdministratorHeading": "{name}の管理者権限を削除しますか?",+ "removeAdministratorDescription": "アカウントとファイルは残りますが、このコンソールは開けなくなります。",+ "signOutEverywhereHeading": "{name}をすべての場所からサインアウトしますか?",+ "signOutEverywhereDescription": "すべてのセッションがすぐに終了します。再びサインインすることはできます。",+ "resetTwoStep": "2段階認証をリセット",+ "resetTwoStepHeading": "{name}の2段階認証をリセットしますか?",+ "resetTwoStepDescription": "認証アプリ、リカバリーコード、パスキーが削除されます。本人はパスワードまたはリンク済みアカウントでサインインし、もう一度設定できます。本人にその旨のメールが届きます。",+ "backToPeople": "すべてのユーザー",+ "personAccount": "アカウント",+ "emailVerified": "確認済み",+ "emailNotVerified": "未確認",+ "joinedRow": "参加日",+ "lastActiveRow": "最終アクティブ",+ "signInMethods": "サインイン方法",+ "twoStepRow": "2段階認証",+ "twoStepNone": "未設定",+ "passkeyCount": {+ "many": "パスキー {count} 件"+ },+ "personWorkspaces": "ワークスペース",+ "personWorkspacesEmpty": "どのワークスペースにも参加していません。",+ "workspaceMembers": {+ "many": "メンバー {count} 人"+ },+ "workspaceRoleAdmin": "管理者",+ "workspaceRoleEditor": "編集者",+ "workspaceRoleViewer": "閲覧者",+ "personSessions": "セッション",+ "noSessions": "どこにもサインインしていません。",+ "personNotFound": "このアカウントは存在しません",+ "personNotFoundDescription": "削除された可能性があります。ユーザーの一覧に戻ってください。","you": "(あなた)","administrator": "管理者","suspended": "停止中",@@ -192,6 +305,11 @@"emailAllSent": "すべて送信済みです","review": "確認","open": "開く",+ "usageSection": "使用状況",+ "accounts": "アカウント",+ "workspaces": "ワークスペース",+ "documents": "ドキュメント",+ "storedFiles": "保存されたファイル","serverSection": "サーバー","serverSectionDescription": "サーバーの設定ファイルで指定します。","deployment": "デプロイ",@@ -207,6 +325,10 @@"someoneElse": "誰か","emailSuppressed": "未送信","emailKindInvitation": "ドキュメントへの招待",+ "emailKindWorkspaceInvitation": "ワークスペースへの招待",+ "emailKindEmailChangeRequested": "メールアドレス変更のリクエスト",+ "emailKindNewSignIn": "新しいサインイン",+ "emailKindTwoStepChanged": "2段階認証の変更","emailKindEnrollmentRequested": "アクセスリクエストの受付","emailKindAdminNotification": "新しいアクセスリクエスト(管理者向け)","emailKindEnrollmentApproved": "アクセスの承認",@@ -225,6 +347,8 @@"activityMadeAdmin": "が管理者に設定:","activityRemovedAdmin": "が管理者権限を削除:","activityEmailRetried": "がメールを再送信:",+ "activityTwoStepReset": "が2段階認証をリセット:",+ "activityReason": "理由:{reason}","activityChanged": "が変更:","errorTitle": "操作できませんでした","errorLastMethod": "サインイン方法を少なくとも1つ残してください。",@@ -235,6 +359,8 @@"errorNotAllowed": "この操作を行う権限がありません。","errorNetwork": "サーバーに接続できませんでした。接続を確認してください。","errorAlreadyDecided": "このリクエストはすでに他の人が対応しました。更新して確認してください。",+ "errorEmailUnchanged": "すでにそのメールアドレスを使用しています。",+ "errorCurrentSession": "使用中のセッションを終了するには、サインアウトしてください。","passwordResetSent": "パスワードを設定するためのリンクをメールでお送りしました。","repeatPassword": "パスワード(確認)","errorNameRequired": "名前を入力してください。",diff --git a/packages/vue/src/i18n/locales/pl/cloud/editor.json b/packages/vue/src/i18n/locales/pl/cloud/editor.jsonindex 66de5a820..01827059d 100644--- a/packages/vue/src/i18n/locales/pl/cloud/editor.json+++ b/packages/vue/src/i18n/locales/pl/cloud/editor.json@@ -262,6 +262,22 @@"removeMember": "Usuń: {name}","pendingInvitations": "Oczekujące","revokeInvitation": "Wycofaj",+ "membersSections": "Obszar roboczy",+ "membersTab": "Członkowie",+ "invitedTab": "Zaproszeni",+ "settingsTab": "Ustawienia",+ "searchMembers": "Szukaj członków…",+ "noMembersMatch": "Nikt nie pasuje do wyszukiwania.",+ "memberJoined": "Dołączył(a) {date}",+ "invitationSent": "Zaproszono {date}",+ "invitationSentBy": "Zaproszono {date} (zaprasza: {name})",+ "resendInvitation": "Wyślij ponownie",+ "invitationResent": "Wysłano ponownie",+ "noInvitations": "Nikt nie czeka na dołączenie",+ "noInvitationsDescription": "Zaproszone osoby będą tu widoczne, dopóki nie przyjmą zaproszenia.",+ "roleAdminDescription": "Zaprasza osoby, zmienia role oraz zmienia nazwę obszaru roboczego lub go usuwa",+ "roleEditorDescription": "Tworzy i edytuje dokumenty obszaru roboczego",+ "roleViewerDescription": "Otwiera dokumenty obszaru roboczego bez ich zmieniania","leaveWorkspace": "Opuść obszar","workspaceAlreadyMember": "Ta osoba już jest w tym obszarze.","workspaceLastAdmin": "Obszar potrzebuje administratora. Najpierw nadaj tę rolę komuś innemu.",diff --git a/packages/vue/src/i18n/locales/pl/cloud/portal.json b/packages/vue/src/i18n/locales/pl/cloud/portal.jsonindex 47092ce75..591be8038 100644--- a/packages/vue/src/i18n/locales/pl/cloud/portal.json+++ b/packages/vue/src/i18n/locales/pl/cloud/portal.json@@ -91,8 +91,12 @@"accountSettings": "Ustawienia konta","sectionAccount": "Twoje konto","sectionServer": "Serwer",+ "profile": "Profil",+ "profileDescription": "Jak widzą Cię inni na {host}.","security": "Logowanie i bezpieczeństwo","securityDescription": "Jak logujesz się do {host}.",+ "sessions": "Sesje",+ "sessionsDescription": "Gdzie i kiedy było zalogowane Twoje konto.","overview": "Przegląd","accessRequests": "Prośby o dostęp","accessRequestsDescription": "Osoby, które chcą dołączyć. Zatwierdzenie pozwala im się zalogować; w obu przypadkach każda z nich dostaje e-mail.",@@ -106,6 +110,49 @@"emailDeliveryDescription": "Zaproszenia, linki do logowania i decyzje o dostępie wysyłane przez serwer.","activity": "Aktywność","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",+ "save": "Zapisz",+ "nameSaved": "Zapisano 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}.",+ "newEmail": "Nowy adres e-mail",+ "sendConfirmation": "Wyślij link",+ "emailChangeSent": "Wysłaliśmy link na adres {email}. Adres zmieni się, gdy go otworzysz.",+ "emailChanged": "Twój adres e-mail to teraz {email}.",+ "emailChangeUnavailable": "Ten serwer nie wysyła e-maili, więc nie możesz tu zmienić adresu e-mail.",+ "accountId": "Identyfikator konta",+ "accountIdDescription": "Podaj go administratorowi, gdy prosisz o pomoc z kontem.",+ "memberSince": "Konto od {date}",+ "activeSessions": "Zalogowane sesje",+ "activeSessionsDescription": "Wyloguj każdą sesję, której nie rozpoznajesz; zakończy się od razu.",+ "signOutOtherSessions": "Wyloguj inne sesje",+ "signOutOtherSessionsHeading": "Wylogować wszystkie inne sesje?",+ "signOutOtherSessionsDescription": "Każda przeglądarka i aplikacja zalogowana na Twoje konto, oprócz tej, będzie musiała zalogować się ponownie.",+ "thisSession": "Ta sesja",+ "desktopApp": "Aplikacja OpenPencil",+ "unknownBrowser": "Nieznana przeglądarka",+ "browserOn": "{browser} w systemie {system}",+ "lastActive": "Aktywność: {when}",+ "signedInOn": "Zalogowano {date}",+ "endSessionHeading": "Wylogować {device}?",+ "endSessionDescription": "Osoba korzystająca z tej sesji będzie musiała zalogować się ponownie.",+ "recentSignIns": "Ostatnie logowania",+ "recentSignInsDescription": "Każde logowanie na Twoje konto. Jeśli któreś nie było Twoje, zmień hasło i wyloguj tę sesję.",+ "noSignIns": "Nie zarejestrowano jeszcze żadnych logowań.",+ "signedInWith": "Za pomocą {method}",+ "methodPassword": "hasła",+ "methodGoogle": "Google",+ "methodApple": "Apple",+ "methodPasskey": "klucza dostępu",+ "methodTwoStep": "logowania dwuetapowego",+ "methodEmailLink": "linku z e-maila",+ "methodDesktop": "aplikacji OpenPencil",+ "methodOther": "innego dostawcy","waysToSignIn": "Metody logowania","waysToSignInDescription": "Zachowaj co najmniej jedną, aby zawsze móc się zalogować.","providerGoogle": "Google",@@ -114,6 +161,8 @@"notLinked": "Niepołączone","link": "Połącz","unlink": "Odłącz",+ "unlinkHeading": "Odłączyć {provider}?",+ "unlinkDescription": "Nie zalogujesz się tą metodą, dopóki nie połączysz jej ponownie.","passwordSet": "Logowanie adresem e-mail i hasłem","passwordNotSet": "Dodaj hasło, aby logować się także adresem e-mail","change": "Zmień",@@ -132,6 +181,8 @@"passkeyAdded": "Dodano {date}","unnamedPasskey": "Klucz dostępu","remove": "Usuń",+ "removePasskeyHeading": "Usunąć {name}?",+ "removePasskeyDescription": "Blokada ekranu tego urządzenia przestanie Cię logować.","noPasskeys": "Brak kluczy dostępu.","adminTwoStepTitle": "Włącz drugi etap logowania","adminTwoStepDescription": "Ten serwer wymaga, aby administratorzy przed otwarciem konsoli używali aplikacji uwierzytelniającej lub klucza dostępu.",@@ -140,7 +191,10 @@"authenticatorSetupKey": "Nie możesz zeskanować? Wpisz ten klucz","recoveryCodesTitle": "Zapisz kody odzyskiwania","recoveryCodesDescription": "Każdy kod pozwala zalogować się raz, jeśli stracisz aplikację uwierzytelniającą. Przechowuj je w bezpiecznym miejscu — nie zostaną pokazane ponownie.",+ "copy": "Kopiuj","copyCodes": "Kopiuj kody",+ "downloadCodes": "Pobierz",+ "recoveryCodesSaveFirst": "Skopiuj lub pobierz kody, zanim przejdziesz dalej.","copyKey": "Kopiuj klucz","copied": "Skopiowano","done": "Gotowe",@@ -160,10 +214,75 @@"reviewedBy": "{decision} ({name})","decline": "Odrzuć","removeAccess": "Odbierz dostęp",+ "declineHeading": "Odrzucić prośbę: {name}?",+ "declineDescription": "Ta osoba dostanie o tym e-mail i może poprosić ponownie później.",+ "removeAccessHeading": "Odebrać dostęp: {name}?",+ "removeAccessDescription": "Ta osoba nie będzie mogła się zalogować i dostanie o tym e-mail.",+ "reviewNote": "Notatka dla administratorów (opcjonalnie)",+ "noteDetail": "Notatka: {note}","noOneWaiting": "Nikt nie czeka","nothingHere": "Nic tu jeszcze nie ma","requestsEmptyDescription": "Nowe prośby pojawią się tutaj, a administratorzy dostaną e-mail o każdej z nich.","searchPeople": "Szukaj użytkowników…",+ "filterEveryone": "Wszyscy",+ "filterAdministrators": "Administratorzy",+ "filterSuspended": "Zawieszeni",+ "filterWithoutTwoStep": "Bez logowania dwuetapowego",+ "twoStepOff": "Bez logowania dwuetapowego",+ "notSignedIn": "Niezalogowany",+ "workspaceCount": {+ "one": "{count} obszar roboczy",+ "few": "{count} obszary robocze",+ "many": "{count} obszarów roboczych"+ },+ "pageRange": "{from}–{to} z {total}",+ "previousPage": "Poprzednia strona",+ "nextPage": "Następna strona",+ "noPeopleFound": "Nikt nie pasuje",+ "noPeopleFoundDescription": "Spróbuj innego imienia, adresu e-mail lub innego filtra.",+ "suspendedReason": "Zawieszono: {reason}",+ "suspendHeading": "Zawiesić konto: {name}?",+ "suspendDescription": "Ta osoba zostanie wylogowana ze wszystkich urządzeń i nie zaloguje się, dopóki nie przywrócisz konta. Jej pliki zostaną.",+ "suspendReason": "Powód (opcjonalnie)",+ "restoreHeading": "Przywrócić konto: {name}?",+ "restoreDescription": "Ta osoba znów będzie mogła się zalogować.",+ "makeAdministratorHeading": "Nadać uprawnienia administratora: {name}?",+ "makeAdministratorDescription": "Administratorzy zatwierdzają konta, zawieszają użytkowników i otwierają tę konsolę.",+ "removeAdministratorHeading": "Odebrać uprawnienia administratora: {name}?",+ "removeAdministratorDescription": "Ta osoba zachowa konto i pliki, ale nie otworzy tej konsoli.",+ "signOutEverywhereHeading": "Wylogować {name} ze wszystkich urządzeń?",+ "signOutEverywhereDescription": "Wszystkie sesje tej osoby zakończą się od razu. Może zalogować się ponownie.",+ "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.",+ "backToPeople": "Wszyscy użytkownicy",+ "personAccount": "Konto",+ "emailVerified": "Potwierdzony",+ "emailNotVerified": "Niepotwierdzony",+ "joinedRow": "Dołączył(a)",+ "lastActiveRow": "Ostatnia aktywność",+ "signInMethods": "Metody logowania",+ "twoStepRow": "Logowanie dwuetapowe",+ "twoStepNone": "Nieskonfigurowane",+ "passkeyCount": {+ "one": "{count} klucz dostępu",+ "few": "{count} klucze dostępu",+ "many": "{count} kluczy dostępu"+ },+ "personWorkspaces": "Obszary robocze",+ "personWorkspacesEmpty": "Nie należy do żadnego obszaru roboczego.",+ "workspaceMembers": {+ "one": "{count} osoba",+ "few": "{count} osoby",+ "many": "{count} osób"+ },+ "workspaceRoleAdmin": "Administrator",+ "workspaceRoleEditor": "Edytujący",+ "workspaceRoleViewer": "Przeglądający",+ "personSessions": "Sesje",+ "noSessions": "Nigdzie niezalogowany.",+ "personNotFound": "Nie ma takiego konta",+ "personNotFoundDescription": "Mogło zostać usunięte. Wróć do listy użytkowników.","you": "(ty)","administrator": "Administrator","suspended": "Zawieszono",@@ -200,6 +319,11 @@"emailAllSent": "Wszystko zostało wysłane","review": "Przejrzyj","open": "Otwórz",+ "usageSection": "Wykorzystanie",+ "accounts": "Konta",+ "workspaces": "Obszary robocze",+ "documents": "Dokumenty",+ "storedFiles": "Przechowywane pliki","serverSection": "Serwer","serverSectionDescription": "Ustawiane w pliku konfiguracyjnym serwera.","deployment": "Wdrożenie",@@ -215,6 +339,10 @@"someoneElse": "Ktoś","emailSuppressed": "Nie wysłano","emailKindInvitation": "Zaproszenie do dokumentu",+ "emailKindWorkspaceInvitation": "Zaproszenie do obszaru roboczego",+ "emailKindEmailChangeRequested": "Prośba o zmianę adresu e-mail",+ "emailKindNewSignIn": "Nowe logowanie",+ "emailKindTwoStepChanged": "Zmiana logowania dwuetapowego","emailKindEnrollmentRequested": "Otrzymano prośbę o dostęp","emailKindAdminNotification": "Nowa prośba o dostęp (administratorzy)","emailKindEnrollmentApproved": "Dostęp zatwierdzony",@@ -233,6 +361,8 @@"activityMadeAdmin": "— nadanie uprawnień administratora:","activityRemovedAdmin": "— odebranie uprawnień administratora:","activityEmailRetried": "— ponowna wysyłka e-maila do:",+ "activityTwoStepReset": "— reset logowania dwuetapowego:",+ "activityReason": "Powód: {reason}","activityChanged": "— zmiana:","errorTitle": "Nie udało się","errorLastMethod": "Zachowaj co najmniej jedną metodę logowania.",@@ -243,6 +373,8 @@"errorNotAllowed": "Nie masz uprawnień do wykonania tej czynności.","errorNetwork": "Nie udało się połączyć z serwerem. Sprawdź połączenie.","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ę.","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/editor.json b/packages/vue/src/i18n/locales/ru/cloud/editor.jsonindex 90c1564e3..dfd2c3ba6 100644--- a/packages/vue/src/i18n/locales/ru/cloud/editor.json+++ b/packages/vue/src/i18n/locales/ru/cloud/editor.json@@ -262,6 +262,22 @@"removeMember": "Удалить: {name}","pendingInvitations": "Ждут присоединения","revokeInvitation": "Отозвать",+ "membersSections": "Рабочее пространство",+ "membersTab": "Участники",+ "invitedTab": "Приглашённые",+ "settingsTab": "Настройки",+ "searchMembers": "Поиск участников…",+ "noMembersMatch": "По этому запросу никого не найдено.",+ "memberJoined": "Присоединение: {date}",+ "invitationSent": "Приглашение: {date}",+ "invitationSentBy": "Приглашение от {name}: {date}",+ "resendInvitation": "Отправить снова",+ "invitationResent": "Отправлено снова",+ "noInvitations": "Никто не ждёт присоединения",+ "noInvitationsDescription": "Приглашённые вами люди появятся здесь, пока не примут приглашение.",+ "roleAdminDescription": "Приглашает людей, меняет роли, переименовывает и удаляет пространство",+ "roleEditorDescription": "Создаёт и редактирует документы пространства",+ "roleViewerDescription": "Открывает документы пространства без возможности их менять","leaveWorkspace": "Покинуть пространство","workspaceAlreadyMember": "Этот человек уже в пространстве.","workspaceLastAdmin": "В пространстве должен быть администратор. Сначала назначьте администратором кого-то другого.",diff --git a/packages/vue/src/i18n/locales/ru/cloud/portal.json b/packages/vue/src/i18n/locales/ru/cloud/portal.jsonindex ceff496f4..b0f06c25d 100644--- a/packages/vue/src/i18n/locales/ru/cloud/portal.json+++ b/packages/vue/src/i18n/locales/ru/cloud/portal.json@@ -91,8 +91,12 @@"accountSettings": "Настройки аккаунта","sectionAccount": "Ваш аккаунт","sectionServer": "Сервер",+ "profile": "Профиль",+ "profileDescription": "Как вас видят другие на {host}.","security": "Вход и безопасность","securityDescription": "Как вы входите на {host}.",+ "sessions": "Сеансы",+ "sessionsDescription": "Где выполнен вход в ваш аккаунт и когда.","overview": "Обзор","accessRequests": "Заявки на доступ","accessRequestsDescription": "Люди, которые хотят присоединиться. После одобрения они смогут войти; в любом случае каждый получит письмо.",@@ -106,6 +110,49 @@"emailDeliveryDescription": "Приглашения, ссылки для входа и решения о доступе, которые отправляет сервер.","activity": "Журнал действий","activityDescription": "Действия администраторов на этом сервере.",+ "detailsSection": "Сведения",+ "detailsSectionDescription": "Ваше имя и фото видны рядом с вашими правками и комментариями.",+ "picture": "Фото",+ "pictureFromProvider": "Из привязанного аккаунта",+ "pictureInitials": "Ваши инициалы, пока вы не привяжете аккаунт с фото",+ "save": "Сохранить",+ "nameSaved": "Имя сохранено",+ "changeEmail": "Изменить почту",+ "changeEmailTitle": "Смена почты",+ "changeEmailDescription": "Мы отправим ссылку на новый адрес. Пока вы не перейдёте по ней, вашей почтой остаётся {email}.",+ "newEmail": "Новая почта",+ "sendConfirmation": "Отправить ссылку",+ "emailChangeSent": "Мы отправили ссылку на {email}. Почта изменится, когда вы перейдёте по ней.",+ "emailChanged": "Теперь ваша почта — {email}.",+ "emailChangeUnavailable": "Этот сервер не отправляет письма, поэтому изменить почту здесь нельзя.",+ "accountId": "ID аккаунта",+ "accountIdDescription": "Сообщите его администратору, когда просите помощи с аккаунтом.",+ "memberSince": "Участник с {date}",+ "activeSessions": "Активные сеансы",+ "activeSessionsDescription": "Завершите любой сеанс, который вам незнаком, — он закончится сразу.",+ "signOutOtherSessions": "Завершить другие сеансы",+ "signOutOtherSessionsHeading": "Завершить все остальные сеансы?",+ "signOutOtherSessionsDescription": "Во всех браузерах и приложениях, где выполнен вход в ваш аккаунт, кроме этого, придётся войти снова.",+ "thisSession": "Этот сеанс",+ "desktopApp": "Приложение OpenPencil",+ "unknownBrowser": "Неизвестный браузер",+ "browserOn": "{browser} на {system}",+ "lastActive": "Активность: {when}",+ "signedInOn": "Вход: {date}",+ "endSessionHeading": "Завершить сеанс «{device}»?",+ "endSessionDescription": "Тому, кто пользуется этим сеансом, придётся войти снова.",+ "recentSignIns": "Недавние входы",+ "recentSignInsDescription": "Все входы в ваш аккаунт. Если какой-то вход выполняли не вы, смените пароль и завершите этот сеанс.",+ "noSignIns": "Входов пока не было.",+ "signedInWith": "С помощью {method}",+ "methodPassword": "пароля",+ "methodGoogle": "Google",+ "methodApple": "Apple",+ "methodPasskey": "ключа доступа",+ "methodTwoStep": "двухэтапного входа",+ "methodEmailLink": "ссылки из письма",+ "methodDesktop": "приложения OpenPencil",+ "methodOther": "другого провайдера","waysToSignIn": "Способы входа","waysToSignInDescription": "Оставьте хотя бы один, чтобы всегда можно было войти.","providerGoogle": "Google",@@ -114,6 +161,8 @@"notLinked": "Не привязан","link": "Привязать","unlink": "Отвязать",+ "unlinkHeading": "Отвязать {provider}?",+ "unlinkDescription": "Входить через него не получится, пока вы снова его не привяжете.","passwordSet": "Вход по почте и паролю","passwordNotSet": "Добавьте пароль, чтобы входить и по почте","change": "Изменить",@@ -132,6 +181,8 @@"passkeyAdded": "Добавлен {date}","unnamedPasskey": "Ключ доступа","remove": "Удалить",+ "removePasskeyHeading": "Удалить {name}?",+ "removePasskeyDescription": "Входить с помощью блокировки экрана этого устройства больше не получится.","noPasskeys": "Ключей доступа пока нет.","adminTwoStepTitle": "Включите второй этап входа","adminTwoStepDescription": "Чтобы открыть консоль, администраторы этого сервера должны использовать приложение-аутентификатор или ключ доступа.",@@ -140,7 +191,10 @@"authenticatorSetupKey": "Не получается отсканировать? Введите этот ключ","recoveryCodesTitle": "Сохраните резервные коды","recoveryCodesDescription": "Каждый код позволяет войти один раз, если вы потеряете аутентификатор. Храните их в надёжном месте — больше они показаны не будут.",+ "copy": "Скопировать","copyCodes": "Скопировать коды",+ "downloadCodes": "Скачать",+ "recoveryCodesSaveFirst": "Прежде чем продолжить, скопируйте или скачайте коды.","copyKey": "Скопировать ключ","copied": "Скопировано","done": "Готово",@@ -160,10 +214,75 @@"reviewedBy": "{decision} ({name})","decline": "Отклонить","removeAccess": "Отозвать доступ",+ "declineHeading": "Отклонить заявку {name}?",+ "declineDescription": "Человек получит письмо об этом и сможет подать заявку позже.",+ "removeAccessHeading": "Отозвать доступ у {name}?",+ "removeAccessDescription": "Человек больше не сможет войти и получит письмо об этом.",+ "reviewNote": "Заметка для администраторов (необязательно)",+ "noteDetail": "Заметка: {note}","noOneWaiting": "Никто не ждёт","nothingHere": "Здесь пока пусто","requestsEmptyDescription": "Новые заявки появятся здесь, а администраторы получат письмо о каждой.","searchPeople": "Поиск пользователей…",+ "filterEveryone": "Все",+ "filterAdministrators": "Администраторы",+ "filterSuspended": "Заблокированные",+ "filterWithoutTwoStep": "Без двухэтапного входа",+ "twoStepOff": "Без двухэтапного входа",+ "notSignedIn": "Входов не было",+ "workspaceCount": {+ "one": "{count} рабочее пространство",+ "few": "{count} рабочих пространства",+ "many": "{count} рабочих пространств"+ },+ "pageRange": "{from}–{to} из {total}",+ "previousPage": "Предыдущая страница",+ "nextPage": "Следующая страница",+ "noPeopleFound": "Никого не найдено",+ "noPeopleFoundDescription": "Попробуйте другое имя, почту или фильтр.",+ "suspendedReason": "Заблокирован: {reason}",+ "suspendHeading": "Заблокировать {name}?",+ "suspendDescription": "Человек выйдет на всех устройствах и не сможет войти, пока вы не восстановите аккаунт. Его файлы сохранятся.",+ "suspendReason": "Причина (необязательно)",+ "restoreHeading": "Восстановить {name}?",+ "restoreDescription": "Человек снова сможет входить.",+ "makeAdministratorHeading": "Сделать {name} администратором?",+ "makeAdministratorDescription": "Администраторы одобряют аккаунты, блокируют пользователей и открывают эту консоль.",+ "removeAdministratorHeading": "Снять права администратора с {name}?",+ "removeAdministratorDescription": "Аккаунт и файлы сохранятся, но открыть эту консоль будет нельзя.",+ "signOutEverywhereHeading": "Завершить все сеансы {name}?",+ "signOutEverywhereDescription": "Все сеансы этого человека сразу завершатся. Он сможет войти снова.",+ "resetTwoStep": "Сбросить двухэтапный вход",+ "resetTwoStepHeading": "Сбросить двухэтапный вход для {name}?",+ "resetTwoStepDescription": "Приложение-аутентификатор, резервные коды и ключи доступа будут удалены: человек сможет войти по паролю или через привязанный аккаунт и настроить их заново. Он получит письмо об этом.",+ "backToPeople": "Все пользователи",+ "personAccount": "Аккаунт",+ "emailVerified": "Подтверждена",+ "emailNotVerified": "Не подтверждена",+ "joinedRow": "Регистрация",+ "lastActiveRow": "Последняя активность",+ "signInMethods": "Способы входа",+ "twoStepRow": "Двухэтапный вход",+ "twoStepNone": "Не настроен",+ "passkeyCount": {+ "one": "{count} ключ доступа",+ "few": "{count} ключа доступа",+ "many": "{count} ключей доступа"+ },+ "personWorkspaces": "Рабочие пространства",+ "personWorkspacesEmpty": "Не состоит ни в одном рабочем пространстве.",+ "workspaceMembers": {+ "one": "{count} участник",+ "few": "{count} участника",+ "many": "{count} участников"+ },+ "workspaceRoleAdmin": "Администратор",+ "workspaceRoleEditor": "Редактор",+ "workspaceRoleViewer": "Читатель",+ "personSessions": "Сеансы",+ "noSessions": "Нигде не выполнен вход.",+ "personNotFound": "Такого аккаунта нет",+ "personNotFoundDescription": "Возможно, его удалили. Вернитесь к списку пользователей.","you": "(вы)","administrator": "Администратор","suspended": "Заблокирован",@@ -200,6 +319,11 @@"emailAllSent": "Всё отправлено","review": "Рассмотреть","open": "Открыть",+ "usageSection": "Использование",+ "accounts": "Аккаунты",+ "workspaces": "Рабочие пространства",+ "documents": "Документы",+ "storedFiles": "Сохранённые файлы","serverSection": "Сервер","serverSectionDescription": "Задаётся в файле конфигурации сервера.","deployment": "Развёртывание",@@ -215,6 +339,10 @@"someoneElse": "Кто-то","emailSuppressed": "Не отправлено","emailKindInvitation": "Приглашение в документ",+ "emailKindWorkspaceInvitation": "Приглашение в рабочее пространство",+ "emailKindEmailChangeRequested": "Запрос на смену почты",+ "emailKindNewSignIn": "Новый вход",+ "emailKindTwoStepChanged": "Двухэтапный вход изменён","emailKindEnrollmentRequested": "Заявка на доступ получена","emailKindAdminNotification": "Новая заявка на доступ (администраторам)","emailKindEnrollmentApproved": "Доступ одобрен",@@ -233,6 +361,8 @@"activityMadeAdmin": "— назначение администратором:","activityRemovedAdmin": "— снятие прав администратора:","activityEmailRetried": "— повторная отправка письма:",+ "activityTwoStepReset": "— сброс двухэтапного входа:",+ "activityReason": "Причина: {reason}","activityChanged": "— изменение:","errorTitle": "Не получилось","errorLastMethod": "Оставьте хотя бы один способ входа.",@@ -243,6 +373,8 @@"errorNotAllowed": "У вас нет прав на это действие.","errorNetwork": "Не удалось связаться с сервером. Проверьте подключение.","errorAlreadyDecided": "По этой заявке уже приняли решение. Обновите страницу, чтобы его увидеть.",+ "errorEmailUnchanged": "Это и так ваша почта.",+ "errorCurrentSession": "Чтобы завершить текущий сеанс, выйдите из аккаунта.","passwordResetSent": "Мы отправили вам ссылку для установки пароля.","repeatPassword": "Повторите пароль","errorNameRequired": "Введите имя.",diff --git a/packages/vue/src/i18n/locales/zh-cn/cloud/editor.json b/packages/vue/src/i18n/locales/zh-cn/cloud/editor.jsonindex 0f6319f9e..7cdd99e5f 100644--- a/packages/vue/src/i18n/locales/zh-cn/cloud/editor.json+++ b/packages/vue/src/i18n/locales/zh-cn/cloud/editor.json@@ -256,6 +256,22 @@"removeMember": "移除 {name}","pendingInvitations": "等待加入","revokeInvitation": "撤回",+ "membersSections": "工作区",+ "membersTab": "成员",+ "invitedTab": "已邀请",+ "settingsTab": "设置",+ "searchMembers": "搜索成员…",+ "noMembersMatch": "没有与搜索匹配的人。",+ "memberJoined": "加入于 {date}",+ "invitationSent": "邀请于 {date}",+ "invitationSentBy": "{name} 邀请于 {date}",+ "resendInvitation": "重新发送",+ "invitationResent": "已重新发送",+ "noInvitations": "没有等待加入的人",+ "noInvitationsDescription": "你邀请的人在接受邀请前会显示在这里。",+ "roleAdminDescription": "可以邀请成员、更改角色,以及重命名或删除工作区",+ "roleEditorDescription": "可以创建和编辑工作区的文档",+ "roleViewerDescription": "可以打开工作区的文档,但不能修改","leaveWorkspace": "离开工作区","workspaceAlreadyMember": "对方已在此工作区中。","workspaceLastAdmin": "工作区需要一名管理员。请先将其他人设为管理员。",diff --git a/packages/vue/src/i18n/locales/zh-cn/cloud/portal.json b/packages/vue/src/i18n/locales/zh-cn/cloud/portal.jsonindex 0e7bb37ef..d9dff5603 100644--- a/packages/vue/src/i18n/locales/zh-cn/cloud/portal.json+++ b/packages/vue/src/i18n/locales/zh-cn/cloud/portal.json@@ -91,8 +91,12 @@"accountSettings": "账号设置","sectionAccount": "你的账号","sectionServer": "服务器",+ "profile": "个人资料",+ "profileDescription": "你在 {host} 上向他人展示的样子。","security": "登录与安全","securityDescription": "你登录 {host} 的方式。",+ "sessions": "会话",+ "sessionsDescription": "你的账号在哪里登录过,以及登录时间。","overview": "概览","accessRequests": "访问申请","accessRequestsDescription": "申请加入的人。批准后即可登录;无论结果如何,对方都会收到邮件。",@@ -104,6 +108,49 @@"emailDeliveryDescription": "服务器发送的邀请、登录链接和访问审核结果。","activity": "活动","activityDescription": "管理员在此服务器上执行的操作。",+ "detailsSection": "详细信息",+ "detailsSectionDescription": "你的名字和头像会显示在你的编辑和评论旁边。",+ "picture": "头像",+ "pictureFromProvider": "来自你关联的账号",+ "pictureInitials": "在你关联带有头像的账号之前,显示你的姓名首字母",+ "save": "保存",+ "nameSaved": "名字已保存",+ "changeEmail": "更改邮箱",+ "changeEmailTitle": "更改你的邮箱",+ "changeEmailDescription": "我们会向新地址发送链接。在你打开链接之前,{email} 仍是你的邮箱。",+ "newEmail": "新邮箱",+ "sendConfirmation": "发送链接",+ "emailChangeSent": "我们已向 {email} 发送链接。打开链接后,你的邮箱才会更改。",+ "emailChanged": "你的邮箱现在是 {email}。",+ "emailChangeUnavailable": "此服务器不发送邮件,因此无法在这里更改你的邮箱。",+ "accountId": "账号 ID",+ "accountIdDescription": "向管理员寻求账号相关帮助时,请提供此 ID。",+ "memberSince": "加入于 {date}",+ "activeSessions": "已登录的会话",+ "activeSessionsDescription": "退出任何你不认识的会话,它会立即结束。",+ "signOutOtherSessions": "退出其他会话",+ "signOutOtherSessionsHeading": "退出其他所有会话?",+ "signOutOtherSessionsDescription": "除当前会话外,所有登录了你账号的浏览器和应用都需要重新登录。",+ "thisSession": "当前会话",+ "desktopApp": "OpenPencil 应用",+ "unknownBrowser": "未知浏览器",+ "browserOn": "{system} 上的 {browser}",+ "lastActive": "{when}活跃",+ "signedInOn": "登录于 {date}",+ "endSessionHeading": "退出 {device}?",+ "endSessionDescription": "使用该会话的人需要重新登录。",+ "recentSignIns": "最近的登录",+ "recentSignInsDescription": "你的账号每次登录的记录。如果某次登录不是你本人,请修改密码并退出该会话。",+ "noSignIns": "暂无登录记录。",+ "signedInWith": "通过{method}登录",+ "methodPassword": "密码",+ "methodGoogle": "Google",+ "methodApple": "Apple",+ "methodPasskey": "通行密钥",+ "methodTwoStep": "两步验证",+ "methodEmailLink": "邮件链接",+ "methodDesktop": "OpenPencil 应用",+ "methodOther": "其他提供方","waysToSignIn": "登录方式","waysToSignInDescription": "请至少保留一种,以便随时能重新登录。","providerGoogle": "Google",@@ -112,6 +159,8 @@"notLinked": "未关联","link": "关联","unlink": "取消关联",+ "unlinkHeading": "取消关联 {provider}?",+ "unlinkDescription": "重新关联之前,你将无法再用它登录。","passwordSet": "使用邮箱和密码登录","passwordNotSet": "添加密码后也可以使用邮箱登录","change": "更改",@@ -130,6 +179,8 @@"passkeyAdded": "添加于 {date}","unnamedPasskey": "通行密钥","remove": "移除",+ "removePasskeyHeading": "移除 {name}?",+ "removePasskeyDescription": "该设备的屏幕锁将不能再用于登录。","noPasskeys": "暂无通行密钥。","adminTwoStepTitle": "开启两步验证","adminTwoStepDescription": "此服务器要求管理员在打开控制台前使用身份验证器应用或通行密钥。",@@ -138,7 +189,10 @@"authenticatorSetupKey": "无法扫描?请输入此密钥","recoveryCodesTitle": "保存你的恢复码","recoveryCodesDescription": "如果无法使用身份验证器,每个恢复码可登录一次。请妥善保管,它们不会再次显示。",+ "copy": "复制","copyCodes": "复制恢复码",+ "downloadCodes": "下载",+ "recoveryCodesSaveFirst": "请先复制或下载恢复码,然后再继续。","copyKey": "复制密钥","copied": "已复制","done": "完成",@@ -158,10 +212,69 @@"reviewedBy": "{decision}({name})","decline": "拒绝","removeAccess": "移除访问权限",+ "declineHeading": "拒绝 {name}?",+ "declineDescription": "对方会收到邮件通知,之后可以再次申请。",+ "removeAccessHeading": "移除 {name} 的访问权限?",+ "removeAccessDescription": "对方将无法再登录,并会收到邮件通知。",+ "reviewNote": "给管理员的备注(可选)",+ "noteDetail": "备注:{note}","noOneWaiting": "没有待处理的申请","nothingHere": "暂无内容","requestsEmptyDescription": "新申请会显示在这里,每条申请都会通过邮件通知管理员。","searchPeople": "搜索成员…",+ "filterEveryone": "所有人",+ "filterAdministrators": "管理员",+ "filterSuspended": "已停用",+ "filterWithoutTwoStep": "未开启两步验证",+ "twoStepOff": "未开启两步验证",+ "notSignedIn": "未登录",+ "workspaceCount": {+ "many": "{count} 个工作区"+ },+ "pageRange": "第 {from}–{to} 项,共 {total} 项",+ "previousPage": "上一页",+ "nextPage": "下一页",+ "noPeopleFound": "没有匹配的人",+ "noPeopleFoundDescription": "请尝试其他名字、邮箱或筛选条件。",+ "suspendedReason": "已停用:{reason}",+ "suspendHeading": "停用 {name}?",+ "suspendDescription": "对方会在所有设备上退出登录,并且在你恢复账号之前无法登录。其文件会保留。",+ "suspendReason": "原因(可选)",+ "restoreHeading": "恢复 {name}?",+ "restoreDescription": "对方可以重新登录。",+ "makeAdministratorHeading": "将 {name} 设为管理员?",+ "makeAdministratorDescription": "管理员可以批准账号、停用用户并打开此控制台。",+ "removeAdministratorHeading": "取消 {name} 的管理员权限?",+ "removeAdministratorDescription": "对方会保留账号和文件,但无法打开此控制台。",+ "signOutEverywhereHeading": "让 {name} 退出所有设备?",+ "signOutEverywhereDescription": "对方的所有会话都会立即结束。对方可以重新登录。",+ "resetTwoStep": "重置两步验证",+ "resetTwoStepHeading": "重置 {name} 的两步验证?",+ "resetTwoStepDescription": "对方的身份验证器应用、恢复码和通行密钥都会被移除,之后可以用密码或关联账号登录并重新设置。对方会收到邮件通知。",+ "backToPeople": "所有成员",+ "personAccount": "账号",+ "emailVerified": "已验证",+ "emailNotVerified": "未验证",+ "joinedRow": "加入时间",+ "lastActiveRow": "最近活跃",+ "signInMethods": "登录方式",+ "twoStepRow": "两步验证",+ "twoStepNone": "未设置",+ "passkeyCount": {+ "many": "{count} 个通行密钥"+ },+ "personWorkspaces": "工作区",+ "personWorkspacesEmpty": "未加入任何工作区。",+ "workspaceMembers": {+ "many": "{count} 名成员"+ },+ "workspaceRoleAdmin": "管理员",+ "workspaceRoleEditor": "编辑者",+ "workspaceRoleViewer": "查看者",+ "personSessions": "会话",+ "noSessions": "未在任何地方登录。",+ "personNotFound": "没有这个账号",+ "personNotFoundDescription": "它可能已被移除。请返回成员列表。","you": "(你)","administrator": "管理员","suspended": "已停用",@@ -192,6 +305,11 @@"emailAllSent": "已全部发送","review": "审核","open": "打开",+ "usageSection": "用量",+ "accounts": "账号",+ "workspaces": "工作区",+ "documents": "文档",+ "storedFiles": "存储的文件","serverSection": "服务器","serverSectionDescription": "在服务器的配置文件中设置。","deployment": "部署方式",@@ -207,6 +325,10 @@"someoneElse": "某人","emailSuppressed": "未发送","emailKindInvitation": "文档邀请",+ "emailKindWorkspaceInvitation": "工作区邀请",+ "emailKindEmailChangeRequested": "邮箱更改申请",+ "emailKindNewSignIn": "新的登录",+ "emailKindTwoStepChanged": "两步验证已更改","emailKindEnrollmentRequested": "已收到访问申请","emailKindAdminNotification": "新的访问申请(管理员)","emailKindEnrollmentApproved": "访问已批准",@@ -225,6 +347,8 @@"activityMadeAdmin": "将以下用户设为管理员:","activityRemovedAdmin": "取消了管理员权限:","activityEmailRetried": "重新发送了邮件给",+ "activityTwoStepReset": "重置了两步验证:",+ "activityReason": "原因:{reason}","activityChanged": "更改了","errorTitle": "操作失败","errorLastMethod": "请至少保留一种登录方式。",@@ -235,6 +359,8 @@"errorNotAllowed": "你没有执行此操作的权限。","errorNetwork": "无法连接到服务器。请检查网络连接。","errorAlreadyDecided": "已有人处理了此申请。请刷新查看。",+ "errorEmailUnchanged": "这已经是你的邮箱了。",+ "errorCurrentSession": "要结束你正在使用的会话,请退出登录。","passwordResetSent": "我们已向你发送设置密码的链接。","repeatPassword": "再次输入密码","errorNameRequired": "请输入你的名字。",diff --git a/packages/vue/src/i18n/messages/cloud/editor.ts b/packages/vue/src/i18n/messages/cloud/editor.tsindex b52f7e63f..cf5a44f89 100644--- a/packages/vue/src/i18n/messages/cloud/editor.ts+++ b/packages/vue/src/i18n/messages/cloud/editor.ts@@ -226,6 +226,22 @@ export const cloudMessageDefaults = {removeMember: params('Remove {name}'),pendingInvitations: 'Waiting to join',revokeInvitation: 'Withdraw',+ membersSections: 'Workspace',+ membersTab: 'Members',+ invitedTab: 'Invited',+ settingsTab: 'Settings',+ searchMembers: 'Search members…',+ noMembersMatch: 'No one matches that search.',+ memberJoined: params('Joined {date}'),+ invitationSent: params('Invited {date}'),+ invitationSentBy: params('Invited {date} by {name}'),+ resendInvitation: 'Resend',+ invitationResent: 'Sent again',+ noInvitations: 'No one is waiting to join',+ noInvitationsDescription: 'People you invite appear here until they accept.',+ roleAdminDescription: 'Invites people, changes roles, and renames or deletes the workspace',+ roleEditorDescription: 'Creates and edits the workspace’s documents',+ roleViewerDescription: 'Opens the workspace’s documents without changing them',leaveWorkspace: 'Leave workspace',leaveWorkspaceHeading: params('Leave {workspace}?'),leaveWorkspaceDescription:diff --git a/packages/vue/src/i18n/messages/cloud/portal.ts b/packages/vue/src/i18n/messages/cloud/portal.tsindex 71afa4a34..52361d314 100644--- a/packages/vue/src/i18n/messages/cloud/portal.ts+++ b/packages/vue/src/i18n/messages/cloud/portal.ts@@ -121,8 +121,12 @@ export const cloudPortalMessageDefaults = {sectionAccount: 'Your account',sectionServer: 'Server',+ profile: 'Profile',+ profileDescription: params('How you appear to people on {host}.'),security: 'Sign-in and security',securityDescription: params('How you sign in to {host}.'),+ sessions: 'Sessions',+ sessionsDescription: 'Where your account is signed in, and when it was.',overview: 'Overview',accessRequests: 'Access requests',accessRequestsDescription:@@ -137,6 +141,55 @@ export const cloudPortalMessageDefaults = {activity: 'Activity',activityDescription: 'What administrators did on this server.',+ 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',+ save: 'Save',+ nameSaved: 'Name saved',+ changeEmail: 'Change email',+ changeEmailTitle: 'Change your email',+ changeEmailDescription: params(+ 'We send a link to the new address. {email} stays your email until you follow it.'+ ),+ newEmail: 'New email',+ sendConfirmation: 'Send link',+ emailChangeSent: params('We sent a link to {email}. Your email changes once you follow it.'),+ emailChanged: params('Your email is now {email}.'),+ emailChangeUnavailable: 'This server doesn’t send email, so your email can’t be changed here.',+ accountId: 'Account ID',+ accountIdDescription: 'Give this to an administrator when you ask for help with your account.',+ memberSince: params('Member since {date}'),++ activeSessions: 'Signed-in sessions',+ activeSessionsDescription: 'Sign out any session you don’t recognize; it ends at once.',+ signOutOtherSessions: 'Sign out other sessions',+ signOutOtherSessionsHeading: 'Sign out of every other session?',+ signOutOtherSessionsDescription:+ 'Every browser and app signed in to your account, except this one, has to sign in again.',+ thisSession: 'This session',+ desktopApp: 'OpenPencil app',+ unknownBrowser: 'Unknown browser',+ browserOn: params('{browser} on {system}'),+ lastActive: params('Active {when}'),+ signedInOn: params('Signed in {date}'),+ endSessionHeading: params('Sign out {device}?'),+ endSessionDescription: 'Whoever uses that session has to sign in again.',+ recentSignIns: 'Recent sign-ins',+ recentSignInsDescription:+ 'Each time your account was signed in. If one wasn’t you, change your password and sign that session out.',+ noSignIns: 'No sign-ins recorded yet.',+ signedInWith: params('With {method}'),+ methodPassword: 'password',+ methodGoogle: 'Google',+ methodApple: 'Apple',+ methodPasskey: 'a passkey',+ methodTwoStep: 'two-step sign-in',+ methodEmailLink: 'an email link',+ methodDesktop: 'the OpenPencil app',+ methodOther: 'another provider',+waysToSignIn: 'Ways to sign in',waysToSignInDescription: 'Keep at least one, so you can always get back in.',providerGoogle: 'Google',@@ -145,6 +198,8 @@ export const cloudPortalMessageDefaults = {notLinked: 'Not linked',link: 'Link',unlink: 'Unlink',+ unlinkHeading: params('Unlink {provider}?'),+ unlinkDescription: 'You can’t sign in with it again until you link it.',passwordSet: 'Sign in with your email and password',passwordNotSet: 'Add a password to sign in with your email too',change: 'Change',@@ -163,6 +218,8 @@ export const cloudPortalMessageDefaults = {passkeyAdded: params('Added {date}'),unnamedPasskey: 'Passkey',remove: 'Remove',+ removePasskeyHeading: params('Remove {name}?'),+ removePasskeyDescription: 'That device’s screen lock stops signing you in.',noPasskeys: 'No passkeys yet.',adminTwoStepTitle: 'Turn on a second sign-in step',adminTwoStepDescription:@@ -174,7 +231,10 @@ export const cloudPortalMessageDefaults = {recoveryCodesTitle: 'Save your recovery codes',recoveryCodesDescription:'Each code signs you in once if you lose your authenticator. Keep them somewhere safe; they won’t be shown again.',+ copy: 'Copy',copyCodes: 'Copy codes',+ downloadCodes: 'Download',+ recoveryCodesSaveFirst: 'Copy or download the codes before you continue.',copyKey: 'Copy key',copied: 'Copied',done: 'Done',@@ -195,10 +255,67 @@ export const cloudPortalMessageDefaults = {reviewedBy: params('{decision} by {name}'),decline: 'Decline',removeAccess: 'Remove access',+ declineHeading: params('Decline {name}?'),+ declineDescription: 'They get an email saying so, and can ask again later.',+ removeAccessHeading: params('Remove access for {name}?'),+ removeAccessDescription: 'They can’t sign in any more, and get an email saying so.',+ reviewNote: 'Note for administrators (optional)',+ noteDetail: params('Note: {note}'),noOneWaiting: 'No one is waiting',nothingHere: 'Nothing here yet',requestsEmptyDescription: 'New requests appear here, and administrators get an email for each.',searchPeople: 'Search people…',+ filterEveryone: 'Everyone',+ filterAdministrators: 'Administrators',+ filterSuspended: 'Suspended',+ filterWithoutTwoStep: 'No two-step',+ twoStepOff: 'No two-step',+ notSignedIn: 'Not signed in',+ workspaceCount: count({ one: '{count} workspace', many: '{count} workspaces' }),+ pageRange: params('{from}–{to} of {total}'),+ previousPage: 'Previous page',+ nextPage: 'Next page',+ noPeopleFound: 'No one matches',+ noPeopleFoundDescription: 'Try another name or email, or another filter.',+ suspendedReason: params('Suspended: {reason}'),+ suspendHeading: params('Suspend {name}?'),+ suspendDescription:+ 'They’re signed out everywhere and can’t sign in until you restore the account. Their files stay.',+ suspendReason: 'Reason (optional)',+ restoreHeading: params('Restore {name}?'),+ restoreDescription: 'They can sign in again.',+ makeAdministratorHeading: params('Make {name} an administrator?'),+ makeAdministratorDescription:+ 'Administrators approve accounts, suspend people, and open this console.',+ removeAdministratorHeading: params('Remove administrator rights from {name}?'),+ removeAdministratorDescription: 'They keep their account and files, but can’t open this console.',+ signOutEverywhereHeading: params('Sign {name} out everywhere?'),+ signOutEverywhereDescription: 'Every session they have ends at once. They can sign in again.',+ resetTwoStep: 'Reset two-step sign-in',+ 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.',++ backToPeople: 'All people',+ personAccount: 'Account',+ emailVerified: 'Verified',+ emailNotVerified: 'Not verified',+ joinedRow: 'Joined',+ lastActiveRow: 'Last active',+ signInMethods: 'Ways to sign in',+ twoStepRow: 'Two-step sign-in',+ twoStepNone: 'Not set up',+ passkeyCount: count({ one: '{count} passkey', many: '{count} passkeys' }),+ personWorkspaces: 'Workspaces',+ personWorkspacesEmpty: 'Not in any workspace.',+ workspaceMembers: count({ one: '{count} member', many: '{count} members' }),+ workspaceRoleAdmin: 'Admin',+ workspaceRoleEditor: 'Editor',+ workspaceRoleViewer: 'Viewer',+ personSessions: 'Sessions',+ noSessions: 'Not signed in anywhere.',+ personNotFound: 'There’s no such account',+ personNotFoundDescription: 'It may have been removed. Go back to the list of people.',you: '(you)',administrator: 'Administrator',suspended: 'Suspended',@@ -229,6 +346,11 @@ export const cloudPortalMessageDefaults = {emailAllSent: 'Everything has been sent',review: 'Review',open: 'Open',+ usageSection: 'Usage',+ accounts: 'Accounts',+ workspaces: 'Workspaces',+ documents: 'Documents',+ storedFiles: 'Stored files',serverSection: 'Server',serverSectionDescription: 'Set in the server’s configuration file.',deployment: 'Deployment',@@ -244,6 +366,10 @@ export const cloudPortalMessageDefaults = {someoneElse: 'Someone',emailSuppressed: 'Not sent',emailKindInvitation: 'Invitation to a document',+ emailKindWorkspaceInvitation: 'Invitation to a workspace',+ emailKindEmailChangeRequested: 'Email change requested',+ emailKindNewSignIn: 'New sign-in',+ emailKindTwoStepChanged: 'Two-step sign-in changed',emailKindEnrollmentRequested: 'Access request received',emailKindAdminNotification: 'New access request (administrators)',emailKindEnrollmentApproved: 'Access approved',@@ -262,6 +388,8 @@ export const cloudPortalMessageDefaults = {activityMadeAdmin: 'made an administrator:',activityRemovedAdmin: 'removed administrator rights from',activityEmailRetried: 'retried an email to',+ activityTwoStepReset: 'reset two-step sign-in for',+ activityReason: params('Reason: {reason}'),activityChanged: 'changed',errorTitle: 'That didn’t work',errorLastMethod: 'Keep at least one way to sign in.',@@ -272,6 +400,8 @@ export const cloudPortalMessageDefaults = {errorNotAllowed: 'You don’t have permission to do that.',errorNetwork: 'Couldn’t reach the server. Check your connection.',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.',passwordResetSent: 'We emailed you a link to set a password.'} as constdiff --git a/src/app/cloud-portal/devices.ts b/src/app/cloud-portal/devices.tsnew file mode 100644index 000000000..dd511c3f7--- /dev/null+++ b/src/app/cloud-portal/devices.ts@@ -0,0 +1,35 @@+import type { CloudSignInMethod } from '@open-pencil/cloud/contract'+import { useCloudPortalMessages } from '@open-pencil/vue/i18n'++/** Words for where a session or sign-in came from, and for how it signed in. */+export function usePortalDeviceLabels() {+ const messages = useCloudPortalMessages()+ function method(value: CloudSignInMethod): string {+ const words = messages.value+ const labels: Record<CloudSignInMethod, string> = {+ password: words.methodPassword,+ google: words.methodGoogle,+ apple: words.methodApple,+ passkey: words.methodPasskey,+ 'two-step': words.methodTwoStep,+ 'email-link': words.methodEmailLink,+ desktop: words.methodDesktop,+ other: words.methodOther+ }+ return labels[value]+ }+ /** The app, or the browser and system the server read, such as "Chrome 141 on macOS". */+ function device(value: {+ method: CloudSignInMethod | null+ browser: string | null+ system: string | null+ }): string {+ const words = messages.value+ if (value.method === 'desktop') return words.desktopApp+ if (value.browser && value.system) {+ return words.browserOn({ browser: value.browser, system: value.system })+ }+ return value.browser ?? value.system ?? words.unknownBrowser+ }+ return { method, device }+}diff --git a/src/app/cloud-portal/failure.ts b/src/app/cloud-portal/failure.tsindex 264238c34..895a186d5 100644--- a/src/app/cloud-portal/failure.ts+++ b/src/app/cloud-portal/failure.ts@@ -36,30 +36,22 @@ export function usePortalFailureMessages() {case 'domain':break}- switch (error.code) {- case 'current_password_invalid':- return value.failureInvalidCredentials- case 'password_too_short':- return value.failurePasswordTooShort- case 'password_too_long':- return value.failurePasswordTooLong- case 'last_authentication_method':- return value.errorLastMethod- case 'session_not_fresh':- return value.errorSessionNotFresh- case 'last_admin_required':- return value.errorLastAdmin- case 'self_admin_action_forbidden':- return value.errorSelfAction- case 'mfa_required':- return value.errorTwoStepRequired- case 'invalid_enrollment_transition':- return value.errorAlreadyDecided- case 'rate_limited':- return value.failureRateLimited- default:- return value.failureUnavailable+ const words: Partial<Record<NonNullable<CloudPortalAPIError['code']>, string>> = {+ current_password_invalid: value.failureInvalidCredentials,+ password_too_short: value.failurePasswordTooShort,+ password_too_long: value.failurePasswordTooLong,+ last_authentication_method: value.errorLastMethod,+ session_not_fresh: value.errorSessionNotFresh,+ last_admin_required: value.errorLastAdmin,+ self_admin_action_forbidden: value.errorSelfAction,+ mfa_required: value.errorTwoStepRequired,+ invalid_enrollment_transition: value.errorAlreadyDecided,+ rate_limited: value.failureRateLimited,+ email_unchanged: value.errorEmailUnchanged,+ email_change_unavailable: value.emailChangeUnavailable,+ current_session: value.errorCurrentSession}+ return (error.code && words[error.code]) ?? value.failureUnavailable}return { failure, callback, api }}diff --git a/src/app/cloud/workspaces/manage.ts b/src/app/cloud/workspaces/manage.tsindex 7c6c19d7b..c49828691 100644--- a/src/app/cloud/workspaces/manage.ts+++ b/src/app/cloud/workspaces/manage.ts@@ -72,6 +72,8 @@ export async function createWorkspace(name: string): Promise<void> {// Memberstype MembersTarget = { serverId: string; workspaceId: string }+/** An invitation just sent and the link it carries. */+export type SentInvitation = { invitationId: string; link: string }export const membersOpen = ref(false)const membersTarget = shallowRef<MembersTarget | null>(null)@@ -79,8 +81,10 @@ export const workspaceMembers = shallowRef<WorkspaceMembers | null>(null)export const membersLoading = ref(false)export const membersBusy = ref(false)export const membersFailure = ref<WorkspaceFailure | null>(null)-/** The link of the invitation just sent, to pass on when the server sends no email. */-export const lastInvitationLink = ref<string | null>(null)+/** The invitation just sent, whose link to pass on when the server sends no email. */+export const lastInvitation = ref<SentInvitation | null>(null)+/** The invitation last sent again and its new link, so its row can say so and offer the link. */+export const lastResent = ref<SentInvitation | null>(null)/** The workspace the dialog manages, as the server last listed it to this person. */export const membersWorkspace = computed(() => {@@ -112,7 +116,8 @@ export async function openWorkspaceMembers(serverId: string, workspaceId: stringmembersTarget.value = { serverId, workspaceId }workspaceMembers.value = nullmembersFailure.value = null- lastInvitationLink.value = null+ lastInvitation.value = null+ lastResent.value = nullmembersOpen.value = truemembersLoading.value = trueawait reload()@@ -146,7 +151,17 @@ async function change(export function inviteToWorkspace(email: string, role: WorkspaceRole): Promise<boolean> {return change(async ({ client, workspaceId }) => {const created = await client.inviteToWorkspace(workspaceId, { email, role })- lastInvitationLink.value = created.acceptanceURL+ lastInvitation.value = { invitationId: created.invitation.id, link: created.acceptanceURL }+ })+}++/** Sends an invitation again under a new link; the one sent before stops working. */+export function resendWorkspaceInvitation(invitationId: string): Promise<boolean> {+ return change(async ({ client, workspaceId }) => {+ const resent = await client.resendWorkspaceInvitation(workspaceId, invitationId)+ lastResent.value = { invitationId: resent.invitation.id, link: resent.acceptanceURL }+ // Its earlier link no longer works, so the note under the invite form goes with it.+ if (lastInvitation.value?.invitationId === invitationId) lastInvitation.value = null})}diff --git a/src/cloud/router.ts b/src/cloud/router.tsindex b06b16272..bd6700bc1 100644--- a/src/cloud/router.ts+++ b/src/cloud/router.ts@@ -82,15 +82,33 @@ export function createCloudPortalRouter(context: PortalContext) {},{path: '/account',+ name: 'profile',+ component: () => import('@/views/cloud/ConsoleView.vue'),+ meta: { account: true }+ },+ {+ path: '/account/security',name: 'security',component: () => import('@/views/cloud/ConsoleView.vue'),meta: { account: true }},+ {+ path: '/account/sessions',+ name: 'sessions',+ component: () => import('@/views/cloud/ConsoleView.vue'),+ meta: { account: true }+ },{path: '/admin/:section(overview|requests|people|email|activity)?',name: 'admin',component: () => import('@/views/cloud/ConsoleView.vue'),meta: { account: true, admin: true }+ },+ {+ path: '/admin/people/:userId',+ name: 'person',+ component: () => import('@/views/cloud/ConsoleView.vue'),+ meta: { account: true, admin: true }}]})diff --git a/src/components/cloud-portal/account/PortalAccountSecurity.vue b/src/components/cloud-portal/account/PortalAccountSecurity.vueindex 7502b7011..3b204573b 100644--- a/src/components/cloud-portal/account/PortalAccountSecurity.vue+++ b/src/components/cloud-portal/account/PortalAccountSecurity.vue@@ -1,5 +1,5 @@<script setup lang="ts">-import { computed } from 'vue'+import { computed, ref } from 'vue'import { useCloudPortalMessages } from '@open-pencil/vue/i18n'@@ -7,6 +7,7 @@ import SettingsGroup from '@/components/settings/layout/SettingsGroup.vue'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 AppConfirmationDialog from '@/components/ui/dialog/AppConfirmationDialog.vue'import AppAlert from '@/components/ui/feedback/AppAlert.vue'import AppBadge from '@/components/ui/feedback/AppBadge.vue'@@ -55,6 +56,35 @@ const social = computed(() =>))const password = computed(() => methods.find((method) => method.provider === 'credential') ?? null)++/** Unlinking or removing a way to sign in is asked once more. */+const confirming = ref<+ | { kind: 'unlink'; id: string; provider: PortalSignInMethod }+ | { kind: 'passkey'; id: string; name: string }+ | null+>(null)+const confirmation = computed(() => {+ const pending = confirming.value+ if (!pending) return null+ const words = messages.value+ return pending.kind === 'unlink'+ ? {+ heading: words.unlinkHeading({ provider: providerLabel(pending.provider) }),+ description: words.unlinkDescription,+ confirm: words.unlink+ }+ : {+ heading: words.removePasskeyHeading({ name: pending.name }),+ description: words.removePasskeyDescription,+ confirm: words.remove+ }+})+function confirm() {+ const pending = confirming.value+ confirming.value = null+ if (pending?.kind === 'unlink') emit('unlink', pending.id)+ else if (pending) emit('removePasskey', pending.id)+}</script><template>@@ -80,7 +110,7 @@ const password = computed(() => methods.find((method) => method.provider === 'crsize="sm"variant="ghost":disabled="busy || !method.canUnlink"- @click="emit('unlink', method.id)"+ @click="confirming = { kind: 'unlink', id: method.id, provider: method.provider }">{{ messages.unlink }}</AppButton>@@ -163,7 +193,13 @@ const password = computed(() => methods.find((method) => method.provider === 'crsize="sm"variant="ghost":disabled="busy"- @click="emit('removePasskey', passkey.id)"+ @click="+ confirming = {+ kind: 'passkey',+ id: passkey.id,+ name: passkey.name ?? messages.unnamedPasskey+ }+ ">{{ messages.remove }}</AppButton>@@ -173,5 +209,16 @@ const password = computed(() => methods.find((method) => method.provider === 'cr{{ messages.noPasskeys }}</p></SettingsSection>++ <AppConfirmationDialog+ :open="confirmation !== null"+ tone="danger"+ :heading="confirmation?.heading ?? ''"+ :description="confirmation?.description"+ :cancel-label="messages.cancel"+ :confirm-label="confirmation?.confirm ?? ''"+ @update:open="(open) => !open && (confirming = null)"+ @confirm="confirm"+ /></div></template>diff --git a/src/components/cloud-portal/account/PortalEmailDialog.vue b/src/components/cloud-portal/account/PortalEmailDialog.vuenew file mode 100644index 000000000..75ece08d2--- /dev/null+++ b/src/components/cloud-portal/account/PortalEmailDialog.vue@@ -0,0 +1,88 @@+<script setup lang="ts">+import * as v from 'valibot'+import { computed, ref, watch } from 'vue'++import { useCloudPortalMessages } from '@open-pencil/vue/i18n'++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'+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. */+const {+ currentEmail,+ error = null,+ saving = false+} = defineProps<{ currentEmail: string; error?: string | null; saving?: boolean }>()+const open = defineModel<boolean>('open', { default: false })+const emit = defineEmits<{ submit: [email: string] }>()++const ui = portalForm()+const messages = useCloudPortalMessages()+const email = ref('')+const invalid = ref<string | null>(null)+watch(open, (value) => {+ if (!value) {+ email.value = ''+ 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)+ if (!result.success) {+ invalid.value = result.issues[0].message+ return+ }+ invalid.value = null+ emit('submit', result.output)+}+</script>++<template>+ <AppDialogRoot v-model:open="open" size="sm">+ <AppDialogHeader+ :heading="messages.changeEmailTitle"+ :description="messages.changeEmailDescription({ email: currentEmail })"+ :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>+ <AppInput+ id="portal-new-email"+ v-model="email"+ type="email"+ autocomplete="email"+ autofocus+ :placeholder="messages.emailPlaceholder"+ :state="invalid ? 'invalid' : 'idle'"+ />+ <p v-if="invalid" :class="ui.error()">{{ invalid }}</p>+ </div>+ </AppDialogBody>+ <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 }}+ </AppButton>+ </AppDialogFooter>+ </form>+ </AppDialogRoot>+</template>diff --git a/src/components/cloud-portal/account/PortalProfile.vue b/src/components/cloud-portal/account/PortalProfile.vuenew file mode 100644index 000000000..8b248be60--- /dev/null+++ b/src/components/cloud-portal/account/PortalProfile.vue@@ -0,0 +1,123 @@+<script setup lang="ts">+import { computed, ref, watch } from 'vue'++import { useCloudPortalMessages } from '@open-pencil/vue/i18n'++import AccountAvatar from '@/components/presence/AccountAvatar.vue'+import SettingsGroup from '@/components/settings/layout/SettingsGroup.vue'+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.+ */+const {+ profile,+ emailChangeAvailable = true,+ busy = false+} = defineProps<{+ profile: {+ id: string+ name: string+ email: string+ image: string | null+ memberSince: string+ }+ /** Whether the server can send the link a new address needs. */+ emailChangeAvailable?: boolean+ busy?: boolean+}>()+const emit = defineEmits<{ rename: [name: string]; changeEmail: [] }>()++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+})+</script>++<template>+ <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">+ <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>++ <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.email"+ :description="emailChangeAvailable ? profile.email : messages.emailChangeUnavailable"+ >+ <AppButton+ v-if="emailChangeAvailable"+ size="sm"+ variant="outline"+ :disabled="busy"+ @click="emit('changeEmail')"+ >+ {{ 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>++ <SettingsSection>+ <template #title>{{ messages.accountId }}</template>+ <template #description>{{ messages.accountIdDescription }}</template>+ <AppCopyField+ :value="profile.id"+ :copy-label="messages.copy"+ :copied-label="messages.copied"+ />+ </SettingsSection>+ </div>+</template>diff --git a/src/components/cloud-portal/account/PortalRecoveryCodes.vue b/src/components/cloud-portal/account/PortalRecoveryCodes.vueindex fe19c7dfb..751dcb8cc 100644--- a/src/components/cloud-portal/account/PortalRecoveryCodes.vue+++ b/src/components/cloud-portal/account/PortalRecoveryCodes.vue@@ -1,20 +1,40 @@<script setup lang="ts">import { useClipboard } from '@vueuse/core'+import { ref } from 'vue'import { useCloudPortalMessages } from '@open-pencil/vue/i18n'+import { downloadBlob } from '@/app/document/io/browser'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'-/** Recovery codes, shown once right after they are made. */+/**+ * Recovery codes, shown once right after they are made. They can't be shown again, so the dialog+ * closes only once they were copied or downloaded.+ */const { codes } = defineProps<{ codes: string[] }>()const open = defineModel<boolean>('open', { default: false })const messages = useCloudPortalMessages()const { copy, copied } = useClipboard({ copiedDuring: 1500 })+const saved = ref(false)++async function copyCodes() {+ await copy(codes.join('\n'))+ saved.value = true+}++function downloadCodes() {+ downloadBlob(+ new TextEncoder().encode(`${codes.join('\n')}\n`),+ 'openpencil-recovery-codes.txt',+ 'text/plain'+ )+ saved.value = true+}</script><template>@@ -30,14 +50,25 @@ const { copy, copied } = useClipboard({ copiedDuring: 1500 })><li v-for="code in codes" :key="code" class="select-all">{{ code }}</li></ul>+ <p v-if="!saved" class="mt-2 text-[11px] text-muted">{{ messages.recoveryCodesSaveFirst }}</p></AppDialogBody>- <AppDialogFooter>- <AppButton variant="outline" @click="copy(codes.join('\n'))">- {{ copied ? messages.copied : messages.copyCodes }}+ <AppDialogFooter :ui="{ footer: 'justify-between' }">+ <div class="flex items-center gap-1">+ <AppButton variant="outline" @click="copyCodes">+ <template #leading>+ <icon-lucide-check v-if="copied" class="size-3.5" />+ <icon-lucide-copy v-else class="size-3.5" />+ </template>+ {{ copied ? messages.copied : messages.copyCodes }}+ </AppButton>+ <AppButton variant="ghost" @click="downloadCodes">+ <template #leading><icon-lucide-download class="size-3.5" /></template>+ {{ messages.downloadCodes }}+ </AppButton>+ </div>+ <AppButton color="primary" variant="solid" :disabled="!saved" @click="open = false">+ {{ messages.done }}</AppButton>- <AppButton color="primary" variant="solid" @click="open = false">{{- messages.done- }}</AppButton></AppDialogFooter></AppDialogRoot></template>diff --git a/src/components/cloud-portal/account/PortalSessions.vue b/src/components/cloud-portal/account/PortalSessions.vuenew file mode 100644index 000000000..af8f420f4--- /dev/null+++ b/src/components/cloud-portal/account/PortalSessions.vue@@ -0,0 +1,152 @@+<script setup lang="ts">+import { compact } from 'es-toolkit'+import { computed, ref } from 'vue'++import { useCloudPortalMessages } from '@open-pencil/vue/i18n'++import { usePortalDeviceLabels } from '@/app/cloud-portal/devices'+import SettingsSection from '@/components/settings/layout/SettingsSection.vue'+import AppButton from '@/components/ui/button/AppButton.vue'+import AppConfirmationDialog from '@/components/ui/dialog/AppConfirmationDialog.vue'+import AppBadge from '@/components/ui/feedback/AppBadge.vue'+import { portalList } from '@/theme/cloud-portal/list'++import type { PortalDevice, PortalSession, PortalSignIn } from '../types'++/**+ * Where an account is signed in and when it signed in. On the person's own account each other+ * session can be signed out, one at a time or all together, each asked once more; an+ * administrator reads them as they are.+ */+const {+ sessions,+ signIns,+ manage = false,+ busy = false+} = defineProps<{+ sessions: PortalSession[]+ signIns: PortalSignIn[]+ /** The person's own sessions, which they can sign out. */+ manage?: boolean+ busy?: boolean+}>()+const emit = defineEmits<{ revoke: [sessionId: string]; revokeOthers: [] }>()++const ui = portalList()+const messages = useCloudPortalMessages()+const labels = usePortalDeviceLabels()+const others = computed(() => sessions.filter((session) => !session.current))+const confirming = ref<{ kind: 'one'; session: PortalSession } | { kind: 'others' } | null>(null)+const confirmation = computed(() => {+ const pending = confirming.value+ if (!pending) return null+ const words = messages.value+ return pending.kind === 'others'+ ? {+ heading: words.signOutOtherSessionsHeading,+ description: words.signOutOtherSessionsDescription,+ confirm: words.signOutOtherSessions+ }+ : {+ heading: words.endSessionHeading({ device: labels.device(pending.session) }),+ description: words.endSessionDescription,+ confirm: words.signOut+ }+})++const detail = (parts: (string | null)[]) => compact(parts).join(' · ')+const signedInWith = (device: PortalDevice) =>+ device.method ? messages.value.signedInWith({ method: labels.method(device.method) }) : null++function confirm() {+ const pending = confirming.value+ confirming.value = null+ if (pending?.kind === 'others') emit('revokeOthers')+ else if (pending) emit('revoke', pending.session.id)+}+</script>++<template>+ <div class="flex max-w-3xl flex-col gap-6">+ <SettingsSection>+ <template #title>{{ messages.activeSessions }}</template>+ <template v-if="manage" #description>{{ messages.activeSessionsDescription }}</template>+ <template v-if="manage && others.length" #actions>+ <AppButton+ size="sm"+ variant="outline"+ :disabled="busy"+ @click="confirming = { kind: 'others' }"+ >+ {{ messages.signOutOtherSessions }}+ </AppButton>+ </template>+ <ul v-if="sessions.length" :class="ui.list()">+ <li v-for="session in sessions" :key="session.id" :class="ui.row()">+ <icon-lucide-app-window+ v-if="session.method === 'desktop'"+ class="size-4 shrink-0 text-muted"+ />+ <icon-lucide-globe v-else class="size-4 shrink-0 text-muted" />+ <div :class="ui.body()">+ <p :class="ui.title()">+ {{ labels.device(session) }}+ <AppBadge v-if="session.current">{{ messages.thisSession }}</AppBadge>+ </p>+ <p :class="ui.detail()">+ {{+ detail([+ messages.lastActive({ when: session.lastActive }),+ session.ipAddress,+ messages.signedInOn({ date: session.signedInOn }),+ signedInWith(session)+ ])+ }}+ </p>+ </div>+ <AppButton+ v-if="manage && !session.current"+ size="sm"+ variant="ghost"+ :disabled="busy"+ @click="confirming = { kind: 'one', session }"+ >+ {{ messages.signOut }}+ </AppButton>+ </li>+ </ul>+ <p v-else class="rounded border border-dashed border-border px-3 py-3 text-xs text-muted">+ {{ messages.noSessions }}+ </p>+ </SettingsSection>++ <SettingsSection>+ <template #title>{{ messages.recentSignIns }}</template>+ <template v-if="manage" #description>{{ messages.recentSignInsDescription }}</template>+ <ul v-if="signIns.length" :class="ui.list()">+ <li v-for="signIn in signIns" :key="signIn.id" :class="ui.row()">+ <icon-lucide-log-in class="size-4 shrink-0 text-muted" />+ <div :class="ui.body()">+ <p :class="ui.title()">{{ labels.device(signIn) }}</p>+ <p :class="ui.detail()">{{ detail([signIn.ipAddress, signedInWith(signIn)]) }}</p>+ </div>+ <span :class="ui.meta()">{{ signIn.when }}</span>+ </li>+ </ul>+ <p v-else class="rounded border border-dashed border-border px-3 py-3 text-xs text-muted">+ {{ messages.noSignIns }}+ </p>+ </SettingsSection>++ <AppConfirmationDialog+ :open="confirmation !== null"+ tone="danger"+ :heading="confirmation?.heading ?? ''"+ :description="confirmation?.description"+ :cancel-label="messages.cancel"+ :confirm-label="confirmation?.confirm ?? ''"+ @update:open="(open) => !open && (confirming = null)"+ @confirm="confirm"+ />+ </div>+</template>diff --git a/src/components/cloud-portal/console/CloudPortalConsole.stories.ts b/src/components/cloud-portal/console/CloudPortalConsole.stories.tsindex 9f7f8d98c..a39df6d44 100644--- a/src/components/cloud-portal/console/CloudPortalConsole.stories.ts+++ b/src/components/cloud-portal/console/CloudPortalConsole.stories.ts@@ -2,22 +2,46 @@ import type { Meta, StoryObj } from '@storybook/vue3-vite'import { ref } from 'vue'import PortalAccountSecurity from '../account/PortalAccountSecurity.vue'+import PortalProfile from '../account/PortalProfile.vue'+import PortalSessions from '../account/PortalSessions.vue'import PortalConsoleLayout from '../layout/PortalConsoleLayout.vue'-import type { AccessRequest, PortalSection } from '../types'+import { PORTAL_SECTION_ICONS } from '../layout/sections'+import type {+ AccessRequest,+ PortalPerson,+ PortalPersonDetail,+ PortalSection,+ PortalSession,+ PortalSignIn+} from '../types'import PortalAccessRequests from './PortalAccessRequests.vue'import PortalActivity from './PortalActivity.vue'import PortalEmailDelivery from './PortalEmailDelivery.vue'import PortalPeople from './PortalPeople.vue'+import PortalPersonPage from './PortalPerson.vue'import PortalStatus from './PortalStatus.vue'const account = { id: 'user-ana', name: 'Ana Duarte', email: '[email protected]' }const sections: PortalSection[] = [- { id: 'security', label: 'Sign-in and security', group: 'Your account' },- { id: 'status', label: 'Overview', group: 'Server' },- { id: 'requests', label: 'Access requests', group: 'Server', count: 3 },- { id: 'people', label: 'People', group: 'Server' },- { id: 'email', label: 'Email delivery', group: 'Server' },- { id: 'activity', label: 'Activity', group: 'Server' }+ { id: 'profile', icon: PORTAL_SECTION_ICONS.profile, label: 'Profile', group: 'Your account' },+ {+ id: 'security',+ icon: PORTAL_SECTION_ICONS.security,+ label: 'Sign-in and security',+ group: 'Your account'+ },+ { id: 'sessions', icon: PORTAL_SECTION_ICONS.sessions, label: 'Sessions', group: 'Your account' },+ { id: 'status', icon: PORTAL_SECTION_ICONS.overview, label: 'Overview', group: 'Server' },+ {+ id: 'requests',+ icon: PORTAL_SECTION_ICONS.requests,+ label: 'Access requests',+ group: 'Server',+ count: 3+ },+ { id: 'people', icon: PORTAL_SECTION_ICONS.people, label: 'People', group: 'Server' },+ { id: 'email', icon: PORTAL_SECTION_ICONS.email, label: 'Email delivery', group: 'Server' },+ { id: 'activity', icon: PORTAL_SECTION_ICONS.activity, label: 'Activity', group: 'Server' }]const requests: AccessRequest[] = [{@@ -45,9 +69,135 @@ const requests: AccessRequest[] = [status: 'pending'}]+const people: PortalPerson[] = [+ {+ id: 'user-ana',+ name: 'Ana Duarte',+ email: '[email protected]',+ admin: true,+ suspended: false,+ twoStep: true,+ joinedOn: 'Mar 3, 2026',+ lastActive: 'now',+ workspaceCount: 3,+ you: true+ },+ {+ id: 'user-ben',+ name: 'Ben Ortiz',+ email: '[email protected]',+ admin: true,+ suspended: false,+ twoStep: true,+ joinedOn: 'Mar 3, 2026',+ lastActive: '2 hr. ago',+ workspaceCount: 2+ },+ {+ id: 'user-mia',+ name: 'Mia Chen',+ email: '[email protected]',+ admin: false,+ suspended: false,+ twoStep: false,+ joinedOn: 'Jun 12, 2026',+ lastActive: 'yesterday',+ workspaceCount: 1+ },+ {+ id: 'user-tom',+ name: 'Tom Weber',+ email: '[email protected]',+ admin: false,+ suspended: true,+ suspendedReason: 'Shared files outside the studio',+ twoStep: false,+ joinedOn: 'Oct 2, 2026',+ lastActive: null,+ workspaceCount: 0+ }+]+const counts = { all: 24, administrators: 2, suspended: 1, 'without-two-step': 9 }+const sessions: PortalSession[] = [+ {+ id: 's1',+ current: true,+ method: 'passkey',+ browser: 'Chrome 141',+ system: 'macOS',+ ipAddress: '203.0.113.9',+ lastActive: 'now',+ signedInOn: 'Oct 20, 2026'+ },+ {+ id: 's2',+ current: false,+ method: 'desktop',+ browser: null,+ system: 'macOS',+ ipAddress: '203.0.113.9',+ lastActive: '3 hr. ago',+ signedInOn: 'Oct 2, 2026'+ },+ {+ id: 's3',+ current: false,+ method: 'google',+ browser: 'Safari 26',+ system: 'iOS',+ ipAddress: '198.51.100.24',+ lastActive: '4 days',+ signedInOn: 'Sep 28, 2026'+ }+]+const signIns: PortalSignIn[] = [+ {+ id: 'i1',+ method: 'passkey',+ browser: 'Chrome 141',+ system: 'macOS',+ ipAddress: '203.0.113.9',+ when: 'Oct 20, 2026, 9:14 AM'+ },+ {+ id: 'i2',+ method: 'desktop',+ browser: null,+ system: 'macOS',+ ipAddress: '203.0.113.9',+ when: 'Oct 2, 2026, 4:05 PM'+ },+ {+ id: 'i3',+ method: 'google',+ browser: 'Safari 26',+ system: 'iOS',+ ipAddress: '198.51.100.24',+ when: 'Sep 28, 2026, 8:40 PM'+ }+]+const person: PortalPersonDetail = {+ person: people[2] ?? people[0],+ emailVerified: true,+ methods: [+ { provider: 'credential', linkedOn: 'Jun 12, 2026' },+ { provider: 'google', linkedOn: 'Jul 1, 2026' }+ ],+ authenticator: false,+ passkeyCount: 0,+ workspaces: [+ { id: 'w1', name: 'Spring campaign', role: 'editor', memberCount: 6 },+ { id: 'w2', name: 'Mia’s workspace', role: 'admin', memberCount: 1 }+ ],+ sessions: sessions.slice(2),+ signIns: signIns.slice(2)+}const components = {PortalConsoleLayout,PortalAccountSecurity,+ PortalProfile,+ PortalSessions,+ PortalPerson: PortalPersonPage,PortalAccessRequests,PortalActivity,PortalEmailDelivery,@@ -73,7 +223,19 @@ const story = (): Story => ({render: () => ({components,- setup: () => ({ account, sections, requests, filter: ref('pending'), ...extra }),+ setup: () => ({+ account,+ sections,+ requests,+ people,+ counts,+ sessions,+ signIns,+ person,+ filter: ref('pending'),+ peopleFilter: ref('all'),+ ...extra+ }),template: `<div class="h-[720px]"><PortalConsoleLayout host="cloud.studio.example" :account="account" :sections="sections" active="${active}" heading="${heading}" description="${description}">@@ -83,6 +245,18 @@ const story = (})})+export const Profile = story(+ 'profile',+ 'Profile',+ 'How you appear to people on cloud.studio.example.',+ `<PortalProfile :profile="{ id: 'user-ana', name: 'Ana Duarte', email: '[email protected]', image: null, memberSince: 'Mar 3, 2026' }" />`+)+export const Sessions = story(+ 'sessions',+ 'Sessions',+ 'Where your account is signed in, and when it was.',+ `<PortalSessions manage :sessions="sessions" :sign-ins="signIns" />`+)export const SignInAndSecurity = story('security','Sign-in and security',@@ -110,7 +284,7 @@ export const Overview = story('status','Overview','cloud.studio.example',- `<PortalStatus :status="{ deployment: 'self-hosted', enrollmentMode: 'approval', emailTransport: 'smtp', pendingEnrollment: 3, pendingEmail: 0, failedEmail: 1 }" />`+ `<PortalStatus :status="{ deployment: 'self-hosted', enrollmentMode: 'approval', emailTransport: 'smtp', pendingEnrollment: 3, pendingEmail: 0, failedEmail: 1, accounts: 24, workspaces: 11, documents: 186, storedBytes: 4831838208 }" />`)export const AccessRequests = story('requests',@@ -128,13 +302,9 @@ export const People = story('people','People','24 accounts on this server.',- `<PortalPeople :people="[- { id: 'user-ana', name: 'Ana Duarte', email: '[email protected]', admin: true, suspended: false, joinedOn: 'in March', you: true },- { id: 'user-ben', name: 'Ben Ortiz', email: '[email protected]', admin: true, suspended: false, joinedOn: 'in March' },- { id: 'user-mia', name: 'Mia Chen', email: '[email protected]', admin: false, suspended: false, joinedOn: 'in June' },- { id: 'user-tom', name: 'Tom Weber', email: '[email protected]', admin: false, suspended: true, joinedOn: 'last week' }- ]" />`+ `<PortalPeople v-model:filter="peopleFilter" :people="people" :counts="counts" :page-size="4" />`)+export const Person = story('people', 'People', '', `<PortalPerson :detail="person" />`)export const EmailDelivery = story('email','Email delivery',@@ -142,6 +312,7 @@ export const EmailDelivery = story(`<PortalEmailDelivery :emails="[{ id: 'e1', kind: 'document-invitation', recipient: '[email protected]', status: 'failed', attempts: 5, when: '10:42', error: 'Mailbox unavailable' },{ id: 'e2', kind: 'email-verification', recipient: '[email protected]', status: 'sent', attempts: 1, when: '09:15' },+ { id: 'e4', kind: 'new-sign-in', recipient: '[email protected]', status: 'sent', attempts: 1, when: '08:51' },{ id: 'e3', kind: 'enrollment-approved', recipient: '[email protected]', status: 'sent', attempts: 1, when: 'Yesterday' }]" />`)@@ -151,7 +322,7 @@ export const Activity = story('What administrators did on this server.',`<PortalActivity :entries="[{ id: 'a1', actor: { id: 'user-ana', name: 'Ana Duarte' }, action: 'enrollment.approved', target: '[email protected]', when: 'Yesterday' },- { id: 'a2', actor: { id: 'user-ben', name: 'Ben Ortiz' }, action: 'user.banned', target: '[email protected]', when: 'Mon' },+ { id: 'a2', actor: { id: 'user-ben', name: 'Ben Ortiz' }, action: 'user.banned', target: 'Tom Weber', reason: 'Shared files outside the studio', when: 'Oct 21, 2026, 11:02 AM' },{ id: 'a3', actor: { id: 'user-ana', name: 'Ana Duarte' }, action: 'user.admin-granted', target: 'Ben Ortiz', when: 'Sep 28' }]" />`)diff --git a/src/components/cloud-portal/console/PortalAccessRequests.vue b/src/components/cloud-portal/console/PortalAccessRequests.vueindex 333936030..52b562766 100644--- a/src/components/cloud-portal/console/PortalAccessRequests.vue+++ b/src/components/cloud-portal/console/PortalAccessRequests.vue@@ -1,12 +1,15 @@<script setup lang="ts">-import { computed } from 'vue'+import { computed, ref } from 'vue'import { useCloudPortalMessages } from '@open-pencil/vue/i18n'import AccountAvatar from '@/components/presence/AccountAvatar.vue'import AppButton from '@/components/ui/button/AppButton.vue'+import AppConfirmationDialog from '@/components/ui/dialog/AppConfirmationDialog.vue'import AppPlaceholder from '@/components/ui/feedback/AppPlaceholder.vue'+import AppTextarea from '@/components/ui/input/AppTextarea.vue'import SegmentedControl from '@/components/ui/select/SegmentedControl.vue'+import { portalForm } from '@/theme/cloud-portal/form'import { portalList } from '@/theme/cloud-portal/list'import type { AccessRequest, AccessRequestStatus } from '../types'@@ -18,9 +21,14 @@ const { requests, busy = null } = defineProps<{busy?: string | null}>()const filter = defineModel<AccessRequestStatus>('filter', { default: 'pending' })-const emit = defineEmits<{ approve: [id: string]; reject: [id: string]; revoke: [id: string] }>()+const emit = defineEmits<{+ approve: [id: string]+ reject: [id: string, note?: string]+ revoke: [id: string, note?: string]+}>()const ui = portalList()+const form = portalForm()const messages = useCloudPortalMessages()const tones = {pending: 'warning',@@ -38,7 +46,43 @@ function detail(request: AccessRequest) {const asked = messages.value.asked({ date: request.requestedOn })if (!request.reviewedBy || request.status === 'pending') return askedconst decision = labels.value[request.status]- return `${asked} · ${messages.value.reviewedBy({ decision, name: request.reviewedBy })}`+ const reviewed = `${asked} · ${messages.value.reviewedBy({ decision, name: request.reviewedBy })}`+ return request.note+ ? `${reviewed} · ${messages.value.noteDetail({ note: request.note })}`+ : reviewed+}++/** Declining or taking access away is asked once more, with a note for the other administrators. */+const confirming = ref<{ kind: 'reject' | 'revoke'; request: AccessRequest } | null>(null)+const note = ref('')+const confirmation = computed(() => {+ const pending = confirming.value+ if (!pending) return null+ const words = messages.value+ const name = pending.request.name ?? pending.request.email+ return pending.kind === 'reject'+ ? {+ heading: words.declineHeading({ name }),+ description: words.declineDescription,+ confirm: words.decline+ }+ : {+ heading: words.removeAccessHeading({ name }),+ description: words.removeAccessDescription,+ confirm: words.removeAccess+ }+})+function ask(kind: 'reject' | 'revoke', request: AccessRequest) {+ note.value = ''+ confirming.value = { kind, request }+}+function confirm() {+ const pending = confirming.value+ confirming.value = null+ if (!pending) return+ const written = note.value.trim() || undefined+ if (pending.kind === 'reject') emit('reject', pending.request.id, written)+ else emit('revoke', pending.request.id, written)}</script>@@ -81,7 +125,7 @@ function detail(request: AccessRequest) {size="sm"variant="ghost":disabled="busy === request.id"- @click="emit('reject', request.id)"+ @click="ask('reject', request)">{{ messages.decline }}</AppButton>@@ -100,7 +144,7 @@ function detail(request: AccessRequest) {size="sm"variant="ghost":loading="busy === request.id"- @click="emit('revoke', request.id)"+ @click="ask('revoke', request)">{{ messages.removeAccess }}</AppButton>@@ -116,5 +160,20 @@ function detail(request: AccessRequest) {><template #icon><icon-lucide-inbox class="size-5" /></template></AppPlaceholder>+ <AppConfirmationDialog+ :open="confirmation !== null"+ tone="danger"+ :heading="confirmation?.heading ?? ''"+ :description="confirmation?.description"+ :cancel-label="messages.cancel"+ :confirm-label="confirmation?.confirm ?? ''"+ @update:open="(open) => !open && (confirming = null)"+ @confirm="confirm"+ >+ <div :class="[form.field(), 'mt-3']">+ <label for="portal-review-note" :class="form.label()">{{ messages.reviewNote }}</label>+ <AppTextarea id="portal-review-note" v-model="note" :rows="2" maxlength="1000" />+ </div>+ </AppConfirmationDialog></div></template>diff --git a/src/components/cloud-portal/console/PortalActivity.vue b/src/components/cloud-portal/console/PortalActivity.vueindex 3e9afa74b..88fc48b92 100644--- a/src/components/cloud-portal/console/PortalActivity.vue+++ b/src/components/cloud-portal/console/PortalActivity.vue@@ -21,7 +21,8 @@ const actions = computed<Record<string, string>>(() => ({'user.sessions-revoked': messages.value.activitySignedOut,'user.admin-granted': messages.value.activityMadeAdmin,'user.admin-revoked': messages.value.activityRemovedAdmin,- 'email.regenerated': messages.value.activityEmailRetried+ 'email.regenerated': messages.value.activityEmailRetried,+ 'user.two-step-reset': messages.value.activityTwoStepReset}))</script>@@ -29,11 +30,16 @@ const actions = computed<Record<string, string>>(() => ({<ul :class="ui.list()"><li v-for="entry in entries" :key="entry.id" :class="ui.row()"><AccountAvatar :id="entry.actor.id" :name="entry.actor.name" />- <p :class="[ui.body(), 'text-xs text-muted']">- <span class="font-medium text-surface">{{ entry.actor.name }}</span>- {{ actions[entry.action] ?? messages.activityChanged }}- <span class="text-surface">{{ entry.target }}</span>- </p>+ <div :class="ui.body()">+ <p class="text-xs text-muted">+ <span class="font-medium text-surface">{{ entry.actor.name }}</span>+ {{ actions[entry.action] ?? messages.activityChanged }}+ <span class="text-surface">{{ entry.target }}</span>+ </p>+ <p v-if="entry.reason" :class="ui.detail()">+ {{ messages.activityReason({ reason: entry.reason }) }}+ </p>+ </div><span :class="ui.meta()">{{ entry.when }}</span></li></ul>diff --git a/src/components/cloud-portal/console/PortalEmailDelivery.vue b/src/components/cloud-portal/console/PortalEmailDelivery.vueindex 43af23540..89997b5f5 100644--- a/src/components/cloud-portal/console/PortalEmailDelivery.vue+++ b/src/components/cloud-portal/console/PortalEmailDelivery.vue@@ -28,6 +28,7 @@ const statusLabels = computed(() => ({}))const kindLabels = computed<Record<string, string>>(() => ({'document-invitation': messages.value.emailKindInvitation,+ 'workspace-invitation': messages.value.emailKindWorkspaceInvitation,'enrollment-requested': messages.value.emailKindEnrollmentRequested,'admin-enrollment-notification': messages.value.emailKindAdminNotification,'enrollment-approved': messages.value.emailKindEnrollmentApproved,@@ -35,7 +36,10 @@ const kindLabels = computed<Record<string, string>>(() => ({'enrollment-revoked': messages.value.emailKindEnrollmentRevoked,'email-verification': messages.value.emailKindVerification,'password-reset': messages.value.emailKindPasswordReset,- 'password-changed': messages.value.emailKindPasswordChanged+ 'password-changed': messages.value.emailKindPasswordChanged,+ 'email-change-requested': messages.value.emailKindEmailChangeRequested,+ 'new-sign-in': messages.value.emailKindNewSignIn,+ 'two-step-changed': messages.value.emailKindTwoStepChanged}))function detail(email: PortalEmail) {const to = messages.value.emailTo({ recipient: email.recipient })diff --git a/src/components/cloud-portal/console/PortalPeople.vue b/src/components/cloud-portal/console/PortalPeople.vueindex d5908e865..ca821a485 100644--- a/src/components/cloud-portal/console/PortalPeople.vue+++ b/src/components/cloud-portal/console/PortalPeople.vue@@ -1,35 +1,69 @@<script setup lang="ts">-import {- DropdownMenuContent,- DropdownMenuItem,- DropdownMenuPortal,- DropdownMenuRoot,- DropdownMenuSeparator,- DropdownMenuTrigger-} from 'reka-ui'+import { computed } from 'vue'+import type { CloudAdminUserFilter } from '@open-pencil/cloud/contract'import { useCloudPortalMessages } from '@open-pencil/vue/i18n'import AccountAvatar from '@/components/presence/AccountAvatar.vue'import IconButton from '@/components/ui/button/IconButton.vue'+import AppPlaceholder from '@/components/ui/feedback/AppPlaceholder.vue'import AppInput from '@/components/ui/input/AppInput.vue'-import { menu } from '@/components/ui/menu/menu'+import SegmentedControl from '@/components/ui/select/SegmentedControl.vue'import { portalList } from '@/theme/cloud-portal/list'-import type { PortalPerson } from '../types'+import type { PortalPerson, PortalPersonAction } from '../types'+import PortalPersonActions from './PortalPersonActions.vue'-/** Everyone with an account on the server, with what an administrator can change about them. */-const { people } = defineProps<{ people: PortalPerson[] }>()+/**+ * Everyone with an account on the server, a page at a time: filtered by what they are, searched+ * by name or email, each with what an administrator can do about them.+ */+const {+ people,+ counts,+ offset = 0,+ pageSize = 50,+ busy = false+} = defineProps<{+ people: PortalPerson[]+ /** How many accounts match the search under each filter. */+ counts: Record<CloudAdminUserFilter, number>+ offset?: number+ pageSize?: number+ busy?: boolean+}>()const query = defineModel<string>('query', { default: '' })+const filter = defineModel<CloudAdminUserFilter>('filter', { default: 'all' })const emit = defineEmits<{- toggleAdmin: [person: PortalPerson]- signOutEverywhere: [person: PortalPerson]- toggleSuspended: [person: PortalPerson]+ act: [person: PortalPerson, action: PortalPersonAction, reason?: string]+ open: [personId: string]+ page: [offset: number]}>()const ui = portalList()-const menuUI = menu()const messages = useCloudPortalMessages()+const total = computed(() => counts[filter.value])+const filters = computed(() => [+ { value: 'all', label: messages.value.filterEveryone },+ { value: 'administrators', label: messages.value.filterAdministrators },+ { value: 'suspended', label: messages.value.filterSuspended },+ { value: 'without-two-step', label: messages.value.filterWithoutTwoStep }+])+const isFilter = (value: string): value is CloudAdminUserFilter =>+ filters.value.some((option) => option.value === value)+const filterValue = computed({+ get: () => filter.value,+ set: (value: string) => {+ if (isFilter(value)) filter.value = value+ }+})+const range = computed(() =>+ messages.value.pageRange({+ from: Math.min(offset + 1, total.value),+ to: Math.min(offset + people.length, total.value),+ total: total.value+ })+)</script><template>@@ -45,60 +79,93 @@ const messages = useCloudPortalMessages()><template #leading><icon-lucide-search class="size-3.5" /></template></AppInput>+ <SegmentedControl v-model="filterValue" required :label="messages.people" :options="filters">+ <template #option="{ option }">+ {{ option.label }}+ <span class="text-muted tabular-nums">+ {{ isFilter(option.value) ? counts[option.value] : '' }}+ </span>+ </template>+ </SegmentedControl></div>- <ul :class="ui.list()">+ <ul v-if="people.length" :class="ui.list()"><li v-for="person in people" :key="person.id" :class="ui.row()">- <AccountAvatar :id="person.id" :name="person.name" size="md" />- <div :class="ui.body()">- <p :class="ui.title()">- {{ person.name }}- <span v-if="person.you" class="font-normal text-muted">{{ messages.you }}</span>- </p>- <p :class="ui.detail()">{{ person.email }}</p>- </div>+ <AccountAvatar :id="person.id" :name="person.name" :image="person.image" size="md" />+ <button+ type="button"+ :class="[+ ui.body(),+ 'rounded text-left focus-visible:ring-2 focus-visible:ring-accent/50 focus-visible:outline-none'+ ]"+ @click="emit('open', person.id)"+ >+ <span :class="ui.title()">+ <span class="truncate">{{ person.name }}</span>+ <span v-if="person.you" class="shrink-0 font-normal text-muted">{{+ messages.you+ }}</span>+ </span>+ <span :class="[ui.detail(), 'block']">+ {{ person.email }}+ <template v-if="person.suspendedReason">+ · {{ messages.suspendedReason({ reason: person.suspendedReason }) }}+ </template>+ </span>+ </button><span v-if="person.admin" :class="ui.status()" data-tone="neutral">{{ messages.administrator }}</span><span v-if="person.suspended" :class="ui.status()" data-tone="error">{{ messages.suspended }}</span>- <span :class="ui.meta()">{{ messages.joined({ date: person.joinedOn }) }}</span>- <DropdownMenuRoot :modal="false">- <DropdownMenuTrigger as-child>- <IconButton :label="messages.actionsFor({ name: person.name })" :disabled="person.you">- <icon-lucide-ellipsis class="size-3.5" />- </IconButton>- </DropdownMenuTrigger>- <DropdownMenuPortal>- <DropdownMenuContent- side="bottom"- align="end"- :side-offset="4"- :class="[menuUI.content(), 'w-52']"- >- <DropdownMenuItem- :class="menuUI.item({ justify: 'start' })"- @select="emit('toggleAdmin', person)"- >- {{ person.admin ? messages.removeAdministrator : messages.makeAdministrator }}- </DropdownMenuItem>- <DropdownMenuItem- :class="menuUI.item({ justify: 'start' })"- @select="emit('signOutEverywhere', person)"- >- {{ messages.signOutEverywhere }}- </DropdownMenuItem>- <DropdownMenuSeparator :class="menuUI.separator()" />- <DropdownMenuItem- :class="menuUI.item({ justify: 'start' })"- @select="emit('toggleSuspended', person)"- >- {{ person.suspended ? messages.restoreAccount : messages.suspendAccount }}- </DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenuPortal>- </DropdownMenuRoot>+ <span v-else-if="person.admin && !person.twoStep" :class="ui.status()" data-tone="warning">+ {{ messages.twoStepOff }}+ </span>+ <span :class="[ui.meta(), 'w-24 text-right']">+ {{ messages.workspaceCount(person.workspaceCount) }}+ </span>+ <span :class="[ui.meta(), 'w-28 text-right']">+ {{+ person.lastActive+ ? messages.lastActive({ when: person.lastActive })+ : messages.notSignedIn+ }}+ </span>+ <span :class="[ui.meta(), 'w-32 text-right']">+ {{ messages.joined({ date: person.joinedOn }) }}+ </span>+ <PortalPersonActions+ :person="person"+ :disabled="busy"+ @act="(action, reason) => emit('act', person, action, reason)"+ /></li></ul>+ <AppPlaceholder+ v-else+ size="compact"+ :fill="false"+ :label="messages.noPeopleFound"+ :description="messages.noPeopleFoundDescription"+ >+ <template #icon><icon-lucide-users class="size-5" /></template>+ </AppPlaceholder>+ <div v-if="total > pageSize" class="flex items-center justify-end gap-1 text-[11px] text-muted">+ <span class="tabular-nums">{{ range }}</span>+ <IconButton+ :label="messages.previousPage"+ :disabled="offset === 0"+ @click="emit('page', Math.max(0, offset - pageSize))"+ >+ <icon-lucide-chevron-left class="size-3.5" />+ </IconButton>+ <IconButton+ :label="messages.nextPage"+ :disabled="offset + people.length >= total"+ @click="emit('page', offset + pageSize)"+ >+ <icon-lucide-chevron-right class="size-3.5" />+ </IconButton>+ </div></div></template>diff --git a/src/components/cloud-portal/console/PortalPerson.vue b/src/components/cloud-portal/console/PortalPerson.vuenew file mode 100644index 000000000..33be72e01--- /dev/null+++ b/src/components/cloud-portal/console/PortalPerson.vue@@ -0,0 +1,134 @@+<script setup lang="ts">+import { compact } from 'es-toolkit'+import { computed } from 'vue'++import type { WorkspaceRole } from '@open-pencil/cloud/contract'+import { useCloudPortalMessages } from '@open-pencil/vue/i18n'++import AccountAvatar from '@/components/presence/AccountAvatar.vue'+import SettingsGroup from '@/components/settings/layout/SettingsGroup.vue'+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 { portalList } from '@/theme/cloud-portal/list'++import PortalSessions from '../account/PortalSessions.vue'+import type { PortalPersonAction, PortalPersonDetail } from '../types'+import PortalPersonActions from './PortalPersonActions.vue'++/**+ * One account as an administrator reads it: its standing, how it signs in, the workspaces it is+ * in, where it is signed in, and what the administrator can do about it.+ */+const { detail, busy = false } = defineProps<{ detail: PortalPersonDetail; busy?: boolean }>()+const emit = defineEmits<{ act: [action: PortalPersonAction, reason?: string]; back: [] }>()++const ui = portalList()+const messages = useCloudPortalMessages()+const person = computed(() => detail.person)++const providers = computed(() =>+ detail.methods+ .map((method) => {+ const words = messages.value+ if (method.provider === 'credential') return words.password+ if (method.provider === 'google') return words.providerGoogle+ if (method.provider === 'apple') return words.providerApple+ return method.provider+ })+ .join(', ')+)+const twoStep = computed(() => {+ const words = messages.value+ const parts = compact([+ detail.authenticator ? words.authenticatorApp : null,+ detail.passkeyCount ? words.passkeyCount(detail.passkeyCount) : null+ ])+ return parts.length ? parts.join(' · ') : words.twoStepNone+})+const roleLabel = (role: WorkspaceRole) =>+ ({+ admin: messages.value.workspaceRoleAdmin,+ editor: messages.value.workspaceRoleEditor,+ viewer: messages.value.workspaceRoleViewer+ })[role]+</script>++<template>+ <div class="flex max-w-3xl flex-col gap-6">+ <AppButton class="self-start" size="sm" variant="ghost" @click="emit('back')">+ <template #leading><icon-lucide-arrow-left class="size-3.5" /></template>+ {{ messages.backToPeople }}+ </AppButton>++ <div class="flex items-center gap-3">+ <AccountAvatar :id="person.id" :name="person.name" :image="person.image" size="lg" />+ <div class="min-w-0 flex-1">+ <p class="flex min-w-0 items-center gap-1.5 text-sm font-semibold text-surface">+ <span class="truncate">{{ person.name }}</span>+ <span v-if="person.you" class="shrink-0 font-normal text-muted">{{ messages.you }}</span>+ <span v-if="person.admin" :class="ui.status()" data-tone="neutral">+ {{ messages.administrator }}+ </span>+ <span v-if="person.suspended" :class="ui.status()" data-tone="error">+ {{ messages.suspended }}+ </span>+ </p>+ <p class="truncate text-xs text-muted">{{ person.email }}</p>+ <p v-if="person.suspendedReason" class="mt-0.5 text-[11px] text-muted">+ {{ messages.suspendedReason({ reason: person.suspendedReason }) }}+ </p>+ </div>+ <PortalPersonActions+ look="button"+ :person="person"+ :disabled="busy"+ @act="(action, reason) => emit('act', action, reason)"+ />+ </div>++ <SettingsSection>+ <template #title>{{ messages.personAccount }}</template>+ <SettingsGroup>+ <SettingsRow+ :label="messages.email"+ :description="+ compact([+ person.email,+ detail.emailVerified ? messages.emailVerified : messages.emailNotVerified+ ]).join(' · ')+ "+ />+ <SettingsRow :label="messages.joinedRow" :description="person.joinedOn" />+ <SettingsRow+ :label="messages.lastActiveRow"+ :description="person.lastActive ?? messages.notSignedIn"+ />+ <SettingsRow+ :label="messages.signInMethods"+ :description="providers || messages.twoStepNone"+ />+ <SettingsRow :label="messages.twoStepRow" :description="twoStep" />+ </SettingsGroup>+ </SettingsSection>++ <SettingsSection>+ <template #title>{{ messages.personWorkspaces }}</template>+ <ul v-if="detail.workspaces.length" :class="ui.list()">+ <li v-for="workspace in detail.workspaces" :key="workspace.id" :class="ui.row()">+ <icon-lucide-layers class="size-4 shrink-0 text-muted" />+ <div :class="ui.body()">+ <p :class="ui.title()">{{ workspace.name }}</p>+ <p :class="ui.detail()">{{ messages.workspaceMembers(workspace.memberCount) }}</p>+ </div>+ <span :class="ui.status()" data-tone="neutral">{{ roleLabel(workspace.role) }}</span>+ </li>+ </ul>+ <p v-else class="rounded border border-dashed border-border px-3 py-3 text-xs text-muted">+ {{ messages.personWorkspacesEmpty }}+ </p>+ </SettingsSection>++ <PortalSessions :sessions="detail.sessions" :sign-ins="detail.signIns" />+ </div>+</template>diff --git a/src/components/cloud-portal/console/PortalPersonActions.vue b/src/components/cloud-portal/console/PortalPersonActions.vuenew file mode 100644index 000000000..e681ade42--- /dev/null+++ b/src/components/cloud-portal/console/PortalPersonActions.vue@@ -0,0 +1,176 @@+<script setup lang="ts">+import {+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuPortal,+ DropdownMenuRoot,+ DropdownMenuSeparator,+ DropdownMenuTrigger+} from 'reka-ui'+import { computed, ref } from 'vue'++import { useCloudPortalMessages } from '@open-pencil/vue/i18n'++import AppButton from '@/components/ui/button/AppButton.vue'+import IconButton from '@/components/ui/button/IconButton.vue'+import AppConfirmationDialog from '@/components/ui/dialog/AppConfirmationDialog.vue'+import AppTextarea from '@/components/ui/input/AppTextarea.vue'+import { menu } from '@/components/ui/menu/menu'+import { portalForm } from '@/theme/cloud-portal/form'++import type { PortalPerson, PortalPersonAction } from '../types'++/**+ * What an administrator can do to an account, in a menu, each asked once more before it happens;+ * suspending also takes a reason for the other administrators.+ */+const {+ person,+ look = 'icon',+ disabled = false+} = defineProps<{+ person: PortalPerson+ /** An icon in a list row, or a labelled button on the person's page. */+ look?: 'icon' | 'button'+ disabled?: boolean+}>()+const emit = defineEmits<{ act: [action: PortalPersonAction, reason?: string] }>()++const messages = useCloudPortalMessages()+const menuUI = menu()+const form = portalForm()+const confirming = ref<PortalPersonAction | null>(null)+const reason = ref('')++const confirmation = computed(() => {+ const action = confirming.value+ if (!action) return null+ const words = messages.value+ const name = person.name+ const copy: Record<+ PortalPersonAction,+ { heading: string; description: string; confirm: string; tone: 'primary' | 'danger' }+ > = {+ 'make-admin': {+ heading: words.makeAdministratorHeading({ name }),+ description: words.makeAdministratorDescription,+ confirm: words.makeAdministrator,+ tone: 'primary'+ },+ 'remove-admin': {+ heading: words.removeAdministratorHeading({ name }),+ description: words.removeAdministratorDescription,+ confirm: words.removeAdministrator,+ tone: 'danger'+ },+ 'sign-out': {+ heading: words.signOutEverywhereHeading({ name }),+ description: words.signOutEverywhereDescription,+ confirm: words.signOutEverywhere,+ tone: 'danger'+ },+ 'reset-two-step': {+ heading: words.resetTwoStepHeading({ name }),+ description: words.resetTwoStepDescription,+ confirm: words.resetTwoStep,+ tone: 'danger'+ },+ suspend: {+ heading: words.suspendHeading({ name }),+ description: words.suspendDescription,+ confirm: words.suspendAccount,+ tone: 'danger'+ },+ restore: {+ heading: words.restoreHeading({ name }),+ description: words.restoreDescription,+ confirm: words.restoreAccount,+ tone: 'primary'+ }+ }+ return copy[action]+})++function ask(action: PortalPersonAction) {+ reason.value = ''+ confirming.value = action+}++function confirm() {+ const action = confirming.value+ confirming.value = null+ if (!action) return+ if (action === 'suspend') emit('act', action, reason.value.trim() || undefined)+ else emit('act', action)+}+</script>++<template>+ <DropdownMenuRoot :modal="false">+ <DropdownMenuTrigger as-child>+ <IconButton+ v-if="look === 'icon'"+ :label="messages.actionsFor({ name: person.name })"+ :disabled="disabled || person.you"+ >+ <icon-lucide-ellipsis class="size-3.5" />+ </IconButton>+ <AppButton+ v-else+ size="sm"+ variant="outline"+ :aria-label="messages.actionsFor({ name: person.name })"+ :disabled="disabled || person.you"+ >+ <icon-lucide-ellipsis class="size-3.5" />+ </AppButton>+ </DropdownMenuTrigger>+ <DropdownMenuPortal>+ <DropdownMenuContent+ side="bottom"+ align="end"+ :side-offset="4"+ :class="[menuUI.content(), 'w-56']"+ >+ <DropdownMenuItem+ :class="menuUI.item({ justify: 'start' })"+ @select="ask(person.admin ? 'remove-admin' : 'make-admin')"+ >+ {{ person.admin ? messages.removeAdministrator : messages.makeAdministrator }}+ </DropdownMenuItem>+ <DropdownMenuItem :class="menuUI.item({ justify: 'start' })" @select="ask('sign-out')">+ {{ messages.signOutEverywhere }}+ </DropdownMenuItem>+ <DropdownMenuItem+ v-if="person.twoStep"+ :class="menuUI.item({ justify: 'start' })"+ @select="ask('reset-two-step')"+ >+ {{ messages.resetTwoStep }}+ </DropdownMenuItem>+ <DropdownMenuSeparator :class="menuUI.separator()" />+ <DropdownMenuItem+ :class="menuUI.item({ justify: 'start' })"+ @select="ask(person.suspended ? 'restore' : 'suspend')"+ >+ {{ person.suspended ? messages.restoreAccount : messages.suspendAccount }}+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenuPortal>+ </DropdownMenuRoot>+ <AppConfirmationDialog+ :open="confirmation !== null"+ :tone="confirmation?.tone"+ :heading="confirmation?.heading ?? ''"+ :description="confirmation?.description"+ :cancel-label="messages.cancel"+ :confirm-label="confirmation?.confirm ?? ''"+ @update:open="(open) => !open && (confirming = null)"+ @confirm="confirm"+ >+ <div v-if="confirming === 'suspend'" :class="[form.field(), 'mt-3']">+ <label for="portal-suspend-reason" :class="form.label()">{{ messages.suspendReason }}</label>+ <AppTextarea id="portal-suspend-reason" v-model="reason" :rows="2" maxlength="500" />+ </div>+ </AppConfirmationDialog>+</template>diff --git a/src/components/cloud-portal/console/PortalStatus.vue b/src/components/cloud-portal/console/PortalStatus.vueindex a054fca2d..e3104cac4 100644--- a/src/components/cloud-portal/console/PortalStatus.vue+++ b/src/components/cloud-portal/console/PortalStatus.vue@@ -3,6 +3,7 @@ import { computed } from 'vue'import { useCloudPortalMessages } from '@open-pencil/vue/i18n'+import { formatStorageBytes } from '@/app/storage/format-bytes'import SettingsGroup from '@/components/settings/layout/SettingsGroup.vue'import SettingsRow from '@/components/settings/layout/SettingsRow.vue'import SettingsSection from '@/components/settings/layout/SettingsSection.vue'@@ -78,6 +79,25 @@ const email = computed(() => {</SettingsRow></SettingsGroup></SettingsSection>+ <SettingsSection>+ <template #title>{{ messages.usageSection }}</template>+ <SettingsGroup>+ <SettingsRow :label="messages.accounts">+ <span class="text-xs text-muted tabular-nums">{{ status.accounts }}</span>+ </SettingsRow>+ <SettingsRow :label="messages.workspaces">+ <span class="text-xs text-muted tabular-nums">{{ status.workspaces }}</span>+ </SettingsRow>+ <SettingsRow :label="messages.documents">+ <span class="text-xs text-muted tabular-nums">{{ status.documents }}</span>+ </SettingsRow>+ <SettingsRow :label="messages.storedFiles">+ <span class="text-xs text-muted tabular-nums">{{+ formatStorageBytes(status.storedBytes)+ }}</span>+ </SettingsRow>+ </SettingsGroup>+ </SettingsSection><SettingsSection><template #title>{{ messages.serverSection }}</template><template #description>{{ messages.serverSectionDescription }}</template>diff --git a/src/components/cloud-portal/layout/PortalConsoleLayout.vue b/src/components/cloud-portal/layout/PortalConsoleLayout.vueindex 732d97c4b..cbec963bf 100644--- a/src/components/cloud-portal/layout/PortalConsoleLayout.vue+++ b/src/components/cloud-portal/layout/PortalConsoleLayout.vue@@ -14,12 +14,11 @@ import type { PortalSection } from '../types'/*** Signed-in Cloud pages: account settings and, for operators, the deployment console. The bar- * leads back to the editor at the server's root; the side list is drawn like the editor's Pages- * panel.+ * leads back to the editor at the server's root.*/const { host, account, sections, active, heading, description } = defineProps<{host: string- account: { id: string; name: string; email: string }+ account: { id: string; name: string; email: string; image?: string | null }sections: PortalSection[]active: stringheading: string@@ -45,7 +44,7 @@ const editorLink = useAppButtonUI({ variant: 'outline', size: 'sm' })<div :class="ui.barEnd()"><a href="/" :class="editorLink.base">{{ messages.openEditor }}</a><span :class="ui.barHost()">{{ account.email }}</span>- <AccountAvatar :id="account.id" :name="account.name" />+ <AccountAvatar :id="account.id" :name="account.name" :image="account.image" /><IconButton :label="messages.signOut" @click="emit('signOut')"><icon-lucide-log-out class="size-3.5" /></IconButton>@@ -67,6 +66,7 @@ const editorLink = useAppButtonUI({ variant: 'outline', size: 'sm' }):aria-current="section.id === active ? 'page' : undefined"@click="emit('select', section.id)">+ <component :is="section.icon" :class="side.icon()" /><span :class="side.label()">{{ section.label }}</span><span v-if="section.count" :class="side.trailing()">{{ section.count }}</span></button>diff --git a/src/components/cloud-portal/layout/sections.ts b/src/components/cloud-portal/layout/sections.tsnew file mode 100644index 000000000..31738a2ca--- /dev/null+++ b/src/components/cloud-portal/layout/sections.ts@@ -0,0 +1,21 @@+import type { Component } from 'vue'+import IconGauge from '~icons/lucide/gauge'+import IconHistory from '~icons/lucide/history'+import IconMail from '~icons/lucide/mail'+import IconMonitorSmartphone from '~icons/lucide/monitor-smartphone'+import IconShieldCheck from '~icons/lucide/shield-check'+import IconUserPlus from '~icons/lucide/user-plus'+import IconUserRound from '~icons/lucide/user-round'+import IconUsers from '~icons/lucide/users'++/** The icon beside each console section in the side list. */+export const PORTAL_SECTION_ICONS = {+ profile: IconUserRound,+ security: IconShieldCheck,+ sessions: IconMonitorSmartphone,+ overview: IconGauge,+ requests: IconUserPlus,+ people: IconUsers,+ email: IconMail,+ activity: IconHistory+} satisfies Record<string, Component>diff --git a/src/components/cloud-portal/sections/AdminActivitySection.vue b/src/components/cloud-portal/sections/AdminActivitySection.vueindex 5c396134c..e28860d29 100644--- a/src/components/cloud-portal/sections/AdminActivitySection.vue+++ b/src/components/cloud-portal/sections/AdminActivitySection.vue@@ -1,4 +1,6 @@<script setup lang="ts">+import * as v from 'valibot'+import { useCloudPortalMessages, useI18n } from '@open-pencil/vue/i18n'import { usePortal } from '@/app/cloud-portal/context'@@ -9,28 +11,26 @@ import AppAlert from '@/components/ui/feedback/AppAlert.vue'import PortalActivity from '../console/PortalActivity.vue'import type { PortalActivityEntry } from '../types'+/** The reason an administrator gave, which the server keeps in the event's metadata. */+const reasonSchema = v.object({ reason: v.string() })+function eventReason(metadata: unknown): string | null {+ const parsed = v.safeParse(reasonSchema, metadata)+ return parsed.success ? parsed.output.reason : null+}+const portal = usePortal()const messages = useCloudPortalMessages()const { locale } = useI18n()const { data: entries, error } = usePortalLoad(async (): Promise<PortalActivityEntry[]> => {- // Events name accounts by ID; the people list gives them names.- const [{ events }, { users }, { enrollments }] = await Promise.all([- portal.api.audit(),- portal.api.users(),- portal.api.enrollments()- ])- const names = new Map(users.map((user) => [user.id, user.name]))- const requesters = new Map(enrollments.map((enrollment) => [enrollment.id, enrollment.email]))+ const { events } = await portal.api.audit()return events.map((event) => ({id: event.id,- actor: {- id: event.actorUserId,- name: names.get(event.actorUserId) ?? messages.value.someoneElse- },+ actor: { id: event.actor.id, name: event.actor.name ?? messages.value.someoneElse },action: event.action,- target: names.get(event.subjectId) ?? requesters.get(event.subjectId) ?? event.subjectId,- when: formatDate(event.createdAt, 'date', locale.value)+ target: event.subject.name ?? event.subject.id,+ reason: eventReason(event.metadata),+ when: formatDate(event.createdAt, 'dateTime', locale.value)}))}, [])</script>diff --git a/src/components/cloud-portal/sections/AdminEmailSection.vue b/src/components/cloud-portal/sections/AdminEmailSection.vueindex 1fedc43e7..4dc67a4c2 100644--- a/src/components/cloud-portal/sections/AdminEmailSection.vue+++ b/src/components/cloud-portal/sections/AdminEmailSection.vue@@ -34,7 +34,7 @@ const {recipient: row.recipientEmailNormalized,status: deliveryStatus(row.status),attempts: row.attemptCount,- when: formatDate(row.nextAttemptAt, 'date', locale.value),+ when: formatDate(row.nextAttemptAt, 'dateTime', locale.value),error: row.lastErrorCode}))}, [])diff --git a/src/components/cloud-portal/sections/AdminPeopleSection.vue b/src/components/cloud-portal/sections/AdminPeopleSection.vueindex f8e0adc1f..1fdb3104b 100644--- a/src/components/cloud-portal/sections/AdminPeopleSection.vue+++ b/src/components/cloud-portal/sections/AdminPeopleSection.vue@@ -2,51 +2,75 @@import { refDebounced } from '@vueuse/core'import { computed, ref, watch } from 'vue'-import { useCloudPortalMessages, useI18n } from '@open-pencil/vue/i18n'+import type { CloudAdminUserFilter } from '@open-pencil/cloud/contract'+import { useCloudPortalMessages } from '@open-pencil/vue/i18n'import { usePortal } from '@/app/cloud-portal/context'import { usePortalAction, usePortalLoad } from '@/app/cloud-portal/state'-import { formatDate } from '@/app/i18n/date'+import { useDateFormat } from '@/app/i18n/date'import AppAlert from '@/components/ui/feedback/AppAlert.vue'import PortalPeople from '../console/PortalPeople.vue'-import type { PortalPerson } from '../types'+import { personAction, portalPerson } from './people'-const emit = defineEmits<{ total: [count: number] }>()+const PAGE_SIZE = 50++/** The accounts on this server, a page at a time, and what administrators do about them. */+const emit = defineEmits<{ total: [count: number]; open: [personId: string] }>()const portal = usePortal()const messages = useCloudPortalMessages()-const { locale } = useI18n()+const dates = useDateFormat()const query = ref('')const search = refDebounced(query, 250)+const filter = ref<CloudAdminUserFilter>('all')+const offset = ref(0)const {data: listing,error: loadError,+ loading,reload-} = usePortalLoad(async (): Promise<{ people: PortalPerson[]; total: number } | null> => {- const { users, total } = await portal.api.users(search.value.trim() || undefined)- const you = portal.account.value?.user.userId- const people = users.map((user) => ({- id: user.id,- name: user.name,- email: user.email,- admin: user.role === 'admin',- suspended: user.banned === true,- joinedOn: formatDate(user.createdAt, 'date', locale.value),- you: user.id === you- }))- return { people, total }-}, null)-const people = computed(() => listing.value?.people ?? [])+} = usePortalLoad(+ () =>+ portal.api.users({+ search: search.value.trim() || undefined,+ filter: filter.value,+ limit: PAGE_SIZE,+ offset: offset.value+ }),+ null+)+// After a failed load the last list belongs to another search or filter, so none is shown.+const people = computed(() =>+ (loadError.value ? [] : (listing.value?.users ?? [])).map((user) =>+ portalPerson(user, portal.account.value?.user.userId, dates)+ )+)+const counts = computed(+ () => listing.value?.counts ?? { all: 0, administrators: 0, suspended: 0, 'without-two-step': 0 }+)-const { error: actionError, run: act } = usePortalAction(async (change: () => Promise<unknown>) => {+const action = usePortalAction(async (change: () => Promise<unknown>) => {await change()await reload()})-const error = computed(() => actionError.value ?? loadError.value)+const error = computed(() => action.error.value ?? loadError.value)-watch(search, () => void reload())-watch(listing, (current) => current && emit('total', current.total))+// A new search or filter starts again from the first page.+watch([search, filter], () => {+ offset.value = 0+ void reload()+})+watch(offset, () => void reload())+watch(listing, (current) => {+ if (!current) return+ emit('total', current.counts.all)+ // A change that empties the last page, such as restoring its only person, steps back a page.+ const total = current.counts[filter.value]+ if (offset.value > 0 && offset.value >= total) {+ offset.value = Math.max(0, Math.floor((total - 1) / PAGE_SIZE) * PAGE_SIZE)+ }+})</script><template>@@ -54,14 +78,17 @@ watch(listing, (current) => current && emit('total', current.total))<AppAlert v-if="error" tone="error" :heading="messages.errorTitle" :description="error" /><PortalPeoplev-model:query="query"+ v-model:filter="filter":people="people"- @toggle-admin="(person) => act(() => portal.api.setAdmin(person.id, !person.admin))"- @sign-out-everywhere="- (person) => act(() => portal.api.userAction('revoke-sessions', person.id))- "- @toggle-suspended="- (person) => act(() => portal.api.userAction(person.suspended ? 'unban' : 'ban', person.id))+ :counts="counts"+ :offset="offset"+ :page-size="PAGE_SIZE"+ :busy="action.busy.value || loading"+ @act="+ (person, kind, reason) => action.run(() => personAction(portal.api, person, kind, reason))"+ @open="(id) => emit('open', id)"+ @page="(next) => (offset = next)"/></div></template>diff --git a/src/components/cloud-portal/sections/AdminPersonSection.vue b/src/components/cloud-portal/sections/AdminPersonSection.vuenew file mode 100644index 000000000..251b63f7a--- /dev/null+++ b/src/components/cloud-portal/sections/AdminPersonSection.vue@@ -0,0 +1,94 @@+<script setup lang="ts">+import { computed, watch } from 'vue'++import { CloudPortalAPIError } from '@open-pencil/cloud/client'+import { useCloudPortalMessages } from '@open-pencil/vue/i18n'++import { usePortal } from '@/app/cloud-portal/context'+import { usePortalAction, usePortalLoad } from '@/app/cloud-portal/state'+import { useDateFormat } from '@/app/i18n/date'+import AppButton from '@/components/ui/button/AppButton.vue'+import AppAlert from '@/components/ui/feedback/AppAlert.vue'+import AppPlaceholder from '@/components/ui/feedback/AppPlaceholder.vue'++import PortalPerson from '../console/PortalPerson.vue'+import type { PortalPersonAction, PortalPersonDetail } from '../types'+import { personAction, portalPerson } from './people'+import { portalSession, portalSignIn } from './sessions'++/** One account's page in the console, and what administrators do about it from there. */+const { userId } = defineProps<{ userId: string }>()+const emit = defineEmits<{ back: [] }>()+const portal = usePortal()+const messages = useCloudPortalMessages()+const dates = useDateFormat()++const loaded = usePortalLoad(async () => {+ try {+ return await portal.api.user(userId)+ } catch (error) {+ if (error instanceof CloudPortalAPIError && error.kind === 'domain') return 'missing' as const+ throw error+ }+}, null)+const detail = computed<PortalPersonDetail | null>(() => {+ const value = loaded.data.value+ if (!value || value === 'missing') return null+ return {+ person: portalPerson(value.user, portal.account.value?.user.userId, dates),+ emailVerified: value.user.emailVerified,+ methods: value.methods.map((method) => ({+ provider: method.provider,+ linkedOn: dates.format(method.createdAt, 'date')+ })),+ authenticator: value.authenticator,+ passkeyCount: value.passkeyCount,+ workspaces: value.workspaces,+ sessions: value.sessions.map((session) => portalSession(session, dates)),+ signIns: value.signIns.map((signIn) => portalSignIn(signIn, dates))+ }+})++const action = usePortalAction(async (change: () => Promise<unknown>) => {+ await change()+ await loaded.reload()+})+const error = computed(() => action.error.value ?? loaded.error.value)++function act(kind: PortalPersonAction, reason?: string) {+ const person = detail.value?.person+ if (person) void action.run(() => personAction(portal.api, person, kind, reason))+}++watch(+ () => userId,+ () => void loaded.reload()+)+</script>++<template>+ <div class="flex flex-col gap-4">+ <AppAlert v-if="error" tone="error" :heading="messages.errorTitle" :description="error" />+ <AppPlaceholder+ v-if="loaded.data.value === 'missing'"+ size="page"+ :label="messages.personNotFound"+ :description="messages.personNotFoundDescription"+ :ui="{ root: 'rounded-lg border border-dashed border-border' }"+ >+ <template #icon><icon-lucide-user-x class="size-5" /></template>+ <template #action>+ <AppButton size="sm" variant="outline" @click="emit('back')">+ {{ messages.backToPeople }}+ </AppButton>+ </template>+ </AppPlaceholder>+ <PortalPerson+ v-else-if="detail"+ :detail="detail"+ :busy="action.busy.value"+ @act="act"+ @back="emit('back')"+ />+ </div>+</template>diff --git a/src/components/cloud-portal/sections/AdminRequestsSection.vue b/src/components/cloud-portal/sections/AdminRequestsSection.vueindex 244d685cc..ae0dac92b 100644--- a/src/components/cloud-portal/sections/AdminRequestsSection.vue+++ b/src/components/cloud-portal/sections/AdminRequestsSection.vue@@ -30,7 +30,8 @@ const {reason: enrollment.reason,requestedOn: formatDate(enrollment.requestedAt, 'date', locale.value),status: enrollment.status,- reviewedBy: enrollment.reviewedBy+ reviewedBy: enrollment.reviewedBy,+ note: enrollment.reviewNote}))}, [])@@ -38,8 +39,8 @@ const {subject: busy,error: reviewError,run: review-} = usePortalAction(async (id: string, action: 'approve' | 'reject' | 'revoke') => {- await portal.api.reviewEnrollment(id, action)+} = usePortalAction(async (id: string, action: 'approve' | 'reject' | 'revoke', note?: string) => {+ await portal.api.reviewEnrollment(id, action, note)emit('changed')await reload()})@@ -56,8 +57,8 @@ watch(filter, () => void reload()):requests="requests":busy="busy"@approve="(id) => review(id, 'approve')"- @reject="(id) => review(id, 'reject')"- @revoke="(id) => review(id, 'revoke')"+ @reject="(id, note) => review(id, 'reject', note)"+ @revoke="(id, note) => review(id, 'revoke', note)"/></div></template>diff --git a/src/components/cloud-portal/sections/ProfileSection.vue b/src/components/cloud-portal/sections/ProfileSection.vuenew file mode 100644index 000000000..cd3e88fe0--- /dev/null+++ b/src/components/cloud-portal/sections/ProfileSection.vue@@ -0,0 +1,155 @@+<script setup lang="ts">+import { computed, onMounted, ref } from 'vue'+import { useRoute, useRouter } from 'vue-router'++import { CloudPortalAPIError } from '@open-pencil/cloud/client'+import { useCloudPortalMessages } from '@open-pencil/vue/i18n'++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 { useDateFormat } from '@/app/i18n/date'+import AppAlert from '@/components/ui/feedback/AppAlert.vue'++import PortalEmailDialog from '../account/PortalEmailDialog.vue'+import PortalPasswordDialog from '../account/PortalPasswordDialog.vue'+import PortalProfile from '../account/PortalProfile.vue'++/** The query the email confirmation link comes back with. */+const EMAIL_CONFIRMED = 'email-confirmed'++/**+ * The signed-in person's name, email, and picture. A new email is confirmed from the new+ * address; a session that signed in a while ago signs in again with its password first.+ */+const portal = usePortal()+const route = useRoute()+const router = useRouter()+const messages = useCloudPortalMessages()+const failures = usePortalFailureMessages()+const dates = useDateFormat()++const loaded = usePortalLoad(async () => {+ const [{ profile }, methods] = await Promise.all([+ portal.api.profile(),+ portal.api.authenticationMethods()+ ])+ return {+ profile,+ hasPassword: methods.methods.some((method) => method.provider === 'credential')+ }+}, null)+const profile = computed(() => {+ const value = loaded.data.value?.profile+ return value+ ? {+ id: value.id,+ name: value.name,+ email: value.email,+ image: value.image,+ memberSince: dates.format(value.createdAt, 'date')+ }+ : null+})+const notice = ref<string | null>(null)++const rename = usePortalAction(async (name: string) => {+ notice.value = null+ await portal.api.updateProfile(name)+ await Promise.all([loaded.reload(), portal.refreshAccount()])+ notice.value = messages.value.nameSaved+})++const emailOpen = ref(false)+const passwordOpen = ref(false)+/** The address waiting for a fresh sign-in before it can be asked for. */+let pendingEmail = ''++async function requestEmail(email: string) {+ await portal.api.changeEmail(email, portalURL(`/account?${EMAIL_CONFIRMED}`))+ emailOpen.value = false+ passwordOpen.value = false+ notice.value = messages.value.emailChangeSent({ email })+}++const changeEmail = usePortalAction(async (email: string) => {+ notice.value = null+ try {+ await requestEmail(email)+ } catch (error) {+ const stale = error instanceof CloudPortalAPIError && error.code === 'session_not_fresh'+ if (!stale || !loaded.data.value?.hasPassword) throw error+ pendingEmail = email+ emailOpen.value = false+ passwordOpen.value = true+ }+})++const confirmPassword = usePortalAction(async (password: string) => {+ const email = portal.account.value?.user.email ?? ''+ const signedIn = await portal.auth.withEmail({ email, password })+ if (!signedIn.ok) {+ confirmPassword.fail(failures.failure(signedIn.failure))+ return+ }+ if (signedIn.value === 'two-step') {+ confirmPassword.fail(failures.failure('session-not-fresh'))+ return+ }+ await requestEmail(pendingEmail)+})++const busy = computed(+ () =>+ loaded.loading.value ||+ rename.busy.value ||+ changeEmail.busy.value ||+ confirmPassword.busy.value+)+const error = computed(() => rename.error.value ?? loaded.error.value)++function openEmail() {+ changeEmail.clear()+ emailOpen.value = true+}++onMounted(async () => {+ if (!(EMAIL_CONFIRMED in route.query)) return+ await router.replace({ query: {} })+ await portal.refreshAccount()+ const email = portal.account.value?.user.email+ if (email) notice.value = 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" />+ <PortalProfile+ v-if="profile"+ :profile="profile"+ :email-change-available="loaded.data.value?.profile.emailChangeAvailable"+ :busy="busy"+ @rename="rename.run"+ @change-email="openEmail"+ />+ <PortalEmailDialog+ v-if="profile"+ v-model:open="emailOpen"+ :current-email="profile.email"+ :error="changeEmail.error.value"+ :saving="busy"+ @submit="changeEmail.run"+ />+ <PortalPasswordDialog+ :open="passwordOpen"+ purpose="confirm"+ :error="confirmPassword.error.value"+ :saving="busy"+ @update:open="(open) => !open && ((passwordOpen = false), confirmPassword.clear())"+ @submit="({ current }) => confirmPassword.run(current)"+ />+ </div>+</template>diff --git a/src/components/cloud-portal/sections/SecuritySection.vue b/src/components/cloud-portal/sections/SecuritySection.vueindex 083d71cae..27546e3ee 100644--- a/src/components/cloud-portal/sections/SecuritySection.vue+++ b/src/components/cloud-portal/sections/SecuritySection.vue@@ -144,7 +144,7 @@ const error = computed(function link(provider: PortalSignInMethod) {void change.run(async () => {- const { url } = await portal.api.linkSocial(provider, portalURL('/account'))+ const { url } = await portal.api.linkSocial(provider, portalURL('/account/security'))globalThis.location.assign(url)})}diff --git a/src/components/cloud-portal/sections/SessionsSection.vue b/src/components/cloud-portal/sections/SessionsSection.vuenew file mode 100644index 000000000..5fd56639a--- /dev/null+++ b/src/components/cloud-portal/sections/SessionsSection.vue@@ -0,0 +1,54 @@+<script setup lang="ts">+import { computed } from 'vue'++import { useCloudPortalMessages } from '@open-pencil/vue/i18n'++import { usePortal } from '@/app/cloud-portal/context'+import { usePortalAction, usePortalLoad } from '@/app/cloud-portal/state'+import { useDateFormat } from '@/app/i18n/date'+import AppAlert from '@/components/ui/feedback/AppAlert.vue'++import PortalSessions from '../account/PortalSessions.vue'+import { portalSession, portalSignIn } from './sessions'++/** Where the signed-in person's account is signed in, its recent sign-ins, and signing them out. */+const portal = usePortal()+const messages = useCloudPortalMessages()+const dates = useDateFormat()++const activity = usePortalLoad(async () => {+ const [{ sessions }, { signIns }] = await Promise.all([+ portal.api.sessions(),+ portal.api.signIns()+ ])+ return { sessions, signIns }+}, null)++const sessions = computed(() =>+ (activity.data.value?.sessions ?? []).map((session) => portalSession(session, dates))+)+const signIns = computed(() =>+ (activity.data.value?.signIns ?? []).map((signIn) => portalSignIn(signIn, dates))+)++const change = usePortalAction(async (work: () => Promise<unknown>) => {+ await work()+ await activity.reload()+})+const error = computed(() => change.error.value ?? activity.error.value)+</script>++<template>+ <div class="flex flex-col gap-4">+ <AppAlert v-if="error" tone="error" :heading="messages.errorTitle" :description="error" />+ <PortalSessions+ v-if="activity.data.value"+ manage+ :sessions="sessions"+ :sign-ins="signIns"+ :busy="change.busy.value"+ @revoke="(id) => change.run(() => portal.api.revokeSession(id))"+ @revoke-others="change.run(() => portal.api.revokeOtherSessions())"+ />+ </div>+</template>diff --git a/src/components/cloud-portal/sections/people.ts b/src/components/cloud-portal/sections/people.tsnew file mode 100644index 000000000..acfa3faf1--- /dev/null+++ b/src/components/cloud-portal/sections/people.ts@@ -0,0 +1,48 @@+import type { CloudPortalClient } from '@open-pencil/cloud/client'+import type { CloudAdminUser } from '@open-pencil/cloud/contract'++import type { useDateFormat } from '@/app/i18n/date'++import type { PortalPerson, PortalPersonAction } from '../types'++type Dates = ReturnType<typeof useDateFormat>++/** An account as the console shows it; `you` marks the administrator's own. */+export function portalPerson(+ user: CloudAdminUser,+ you: string | undefined,+ dates: Dates+): PortalPerson {+ return {+ id: user.id,+ name: user.name,+ email: user.email,+ image: user.image,+ admin: user.role === 'admin',+ suspended: user.banned === true,+ suspendedReason: user.banned ? (user.banReason ?? null) : null,+ twoStep: user.twoStep,+ joinedOn: dates.format(user.createdAt, 'date'),+ lastActive: user.lastActiveAt ? dates.relative(user.lastActiveAt) : null,+ workspaceCount: user.workspaceCount,+ you: user.id === you+ }+}++/** Asks the server to do what an administrator confirmed. */+export function personAction(+ api: CloudPortalClient,+ person: PortalPerson,+ action: PortalPersonAction,+ reason?: string+): Promise<unknown> {+ const requests: Record<PortalPersonAction, () => Promise<unknown>> = {+ 'make-admin': () => api.setAdmin(person.id, true),+ '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),+ suspend: () => api.userAction('ban', person.id, reason),+ restore: () => api.userAction('unban', person.id)+ }+ return requests[action]()+}diff --git a/src/components/cloud-portal/sections/sessions.ts b/src/components/cloud-portal/sections/sessions.tsnew file mode 100644index 000000000..e9f648b46--- /dev/null+++ b/src/components/cloud-portal/sections/sessions.ts@@ -0,0 +1,32 @@+import type { CloudAccountSession, CloudSignIn } from '@open-pencil/cloud/contract'++import type { useDateFormat } from '@/app/i18n/date'++import type { PortalSession, PortalSignIn } from '../types'++type Dates = ReturnType<typeof useDateFormat>++/** A session as the portal lists it, with its dates in words. */+export function portalSession(session: CloudAccountSession, dates: Dates): PortalSession {+ return {+ id: session.id,+ current: session.current,+ method: session.method,+ browser: session.browser,+ system: session.system,+ ipAddress: session.ipAddress,+ lastActive: dates.relative(session.lastActiveAt),+ signedInOn: dates.format(session.createdAt, 'date')+ }+}++export function portalSignIn(signIn: CloudSignIn, dates: Dates): PortalSignIn {+ return {+ id: signIn.id,+ method: signIn.method,+ browser: signIn.browser,+ system: signIn.system,+ ipAddress: signIn.ipAddress,+ when: dates.format(signIn.createdAt, 'dateTime')+ }+}diff --git a/src/components/cloud-portal/types.ts b/src/components/cloud-portal/types.tsindex ea3c172bf..063dad8c3 100644--- a/src/components/cloud-portal/types.ts+++ b/src/components/cloud-portal/types.ts@@ -1,6 +1,11 @@+import type { Component } from 'vue'++import type { CloudSignInMethod, WorkspaceRole } from '@open-pencil/cloud/contract'+export type PortalSection = {id: stringlabel: string+ icon: Componentgroup: stringcount?: number}@@ -17,18 +22,68 @@ export type AccessRequest = {requestedOn: stringstatus: AccessRequestStatusreviewedBy?: string | null+ /** What the administrator who decided wrote down for the others. */+ note?: string | null}export type PortalPerson = {id: stringname: stringemail: string+ image?: string | nulladmin: booleansuspended: boolean+ /** Why an administrator suspended the account, when they said. */+ suspendedReason?: string | null+ /** An authenticator app or a passkey confirms the account's sign-ins. */+ twoStep: booleanjoinedOn: string+ /** When one of its sessions was last used, already worded; null when none is left. */+ lastActive: string | null+ workspaceCount: numberyou?: boolean}+/** Something an administrator does to an account, each asked once more before it happens. */+export type PortalPersonAction =+ | 'make-admin'+ | 'remove-admin'+ | 'sign-out'+ | 'reset-two-step'+ | 'suspend'+ | 'restore'++/** What the server read about the browser or app a session or sign-in came from. */+export type PortalDevice = {+ method: CloudSignInMethod | null+ browser: string | null+ system: string | null+ ipAddress: string | null+}++export type PortalSession = PortalDevice & {+ id: string+ current: boolean+ lastActive: string+ signedInOn: string+}++export type PortalSignIn = PortalDevice & {+ id: string+ when: string+}++export type PortalPersonDetail = {+ person: PortalPerson+ emailVerified: boolean+ methods: { provider: string; linkedOn: string }[]+ authenticator: boolean+ passkeyCount: number+ workspaces: { id: string; name: string; role: WorkspaceRole; memberCount: number }[]+ sessions: PortalSession[]+ signIns: PortalSignIn[]+}+export type PortalEmail = {id: stringkind: string@@ -45,6 +100,8 @@ export type PortalActivityEntry = {/** The server's action code, such as `enrollment.approved`. */action: stringtarget: string+ /** Why the administrator did it, when they said. */+ reason?: string | nullwhen: string}@@ -62,4 +119,8 @@ export type PortalServerStatus = {pendingEnrollment: numberpendingEmail: numberfailedEmail: number+ accounts: number+ workspaces: number+ documents: number+ storedBytes: number}diff --git a/src/components/cloud/workspace/CloudWorkspaceMembersDialog.stories.ts b/src/components/cloud/workspace/CloudWorkspaceMembersDialog.stories.tsnew file mode 100644index 000000000..053b7abcf--- /dev/null+++ b/src/components/cloud/workspace/CloudWorkspaceMembersDialog.stories.ts@@ -0,0 +1,107 @@+import type { Meta, StoryObj } from '@storybook/vue3-vite'+import { expect, fn, userEvent, within } from 'storybook/test'++import type { WorkspaceMembers } from '@open-pencil/cloud/contract'++import CloudWorkspaceMembersDialog from './CloudWorkspaceMembersDialog.vue'++type Args = {+ members: WorkspaceMembers+ canManage: boolean+ resent: { invitationId: string; link: string } | null+ onResend: (invitationId: string) => void+}++const members: WorkspaceMembers = {+ members: [+ {+ userId: 'user-ana',+ name: 'Ana Duarte',+ email: '[email protected]',+ image: null,+ role: 'admin',+ joinedAt: '2026-03-03T09:00:00.000Z'+ },+ {+ userId: 'user-ben',+ name: 'Ben Ortiz',+ email: '[email protected]',+ image: null,+ role: 'editor',+ joinedAt: '2026-04-11T09:00:00.000Z'+ },+ {+ userId: 'user-mia',+ name: 'Mia Chen',+ email: '[email protected]',+ image: null,+ role: 'viewer',+ joinedAt: '2026-06-12T09:00:00.000Z'+ }+ ],+ invitations: [+ {+ id: '6f1d3a52-1d4e-4c7b-9a1e-2f9b9c1a0d11',+ email: '[email protected]',+ role: 'editor',+ invitedBy: { id: 'user-ana', name: 'Ana Duarte' },+ invitedAt: '2026-10-20T09:00:00.000Z',+ expiresAt: '2026-10-27T09:00:00.000Z'+ }+ ]+}++const meta = {+ title: 'App/Cloud/Workspace Members',+ tags: ['autodocs'],+ args: { members, canManage: true, resent: null, onResend: fn() },+ render: (args) => ({+ components: { CloudWorkspaceMembersDialog },+ setup: () => ({ args }),+ template: `+ <div class="h-[640px]">+ <CloudWorkspaceMembersDialog+ :open="true"+ workspace-name="Spring campaign"+ self="user-ana"+ :can-manage="args.canManage"+ :members="args.members"+ :resent="args.resent"+ @resend="args.onResend"+ />+ </div>`+ })+} satisfies Meta<Args>++export default meta+type Story = StoryObj<typeof meta>++export const Members: Story = {}++export const Invited: Story = {+ play: async ({ args }) => {+ const page = within(document.body)+ await userEvent.click(await page.findByRole('tab', { name: /Invited/ }))+ await userEvent.click(await page.findByRole('button', { name: 'Resend' }))+ await expect(args.onResend).toHaveBeenCalledWith('6f1d3a52-1d4e-4c7b-9a1e-2f9b9c1a0d11')+ }+}++export const InvitationSentAgain: Story = {+ args: {+ resent: {+ invitationId: '6f1d3a52-1d4e-4c7b-9a1e-2f9b9c1a0d11',+ link: 'https://cloud.studio.example/invitations/accept#token'+ }+ },+ play: async () => {+ const page = within(document.body)+ await userEvent.click(await page.findByRole('tab', { name: /Invited/ }))+ await expect(page.queryByRole('button', { name: 'Resend' })).toBeNull()+ await expect(page.getByRole('button', { name: 'Copy invitation link' })).toBeVisible()+ }+}++export const MemberCannotManage: Story = {+ args: { canManage: false, members: { ...members, invitations: [] } }+}diff --git a/src/components/cloud/workspace/CloudWorkspaceMembersDialog.vue b/src/components/cloud/workspace/CloudWorkspaceMembersDialog.vueindex 85b03c365..7d1d752b5 100644--- a/src/components/cloud/workspace/CloudWorkspaceMembersDialog.vue+++ b/src/components/cloud/workspace/CloudWorkspaceMembersDialog.vue@@ -5,22 +5,34 @@ import { computed, ref, watch } from 'vue'import type { WorkspaceMembers, WorkspaceRole } from '@open-pencil/cloud/contract'import { useCloudMessages, useCommonMessages } from '@open-pencil/vue/i18n'+import { useDateFormat } from '@/app/i18n/date'import AccountAvatar from '@/components/presence/AccountAvatar.vue'import AppButton from '@/components/ui/button/AppButton.vue'+import IconButton from '@/components/ui/button/IconButton.vue'import AppConfirmationDialog from '@/components/ui/dialog/AppConfirmationDialog.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'+import AppBadge from '@/components/ui/feedback/AppBadge.vue'+import AppPlaceholder from '@/components/ui/feedback/AppPlaceholder.vue'import AppInput from '@/components/ui/input/AppInput.vue'import AppSelect from '@/components/ui/select/AppSelect.vue'+import AppTabsContent from '@/components/ui/tabs/AppTabsContent.vue'+import AppTabsList from '@/components/ui/tabs/AppTabsList.vue'+import AppTabsRoot from '@/components/ui/tabs/AppTabsRoot.vue'+import AppTabsTrigger from '@/components/ui/tabs/AppTabsTrigger.vue'import { cloudWorkspace } from '@/theme/cloud/workspace'+/** Past this many members the list gets a search field. */+const MEMBER_SEARCH_THRESHOLD = 8+/**- * Who belongs to a Cloud workspace. Administrators rename it, invite people by email with a- * role, change roles, and remove people; everyone sees the members and may leave. Leaving and- * deleting sit apart in a danger zone, and deleting asks for the workspace's name.+ * Who belongs to a Cloud workspace, in tabs. Members lists everyone, with when they joined, and+ * lets administrators invite people with a role, change roles, and remove people; Invited shows+ * who hasn't joined yet, who invited them and until when, to send again or withdraw; Settings+ * renames the workspace and holds leaving and deleting apart, deleting asking for its name.*/const {workspaceName,@@ -30,7 +42,8 @@ const {loading = false,busy = false,failure = null,- invitationLink = null+ invitationLink = null,+ resent = null} = defineProps<{workspaceName: string/** The person administers the workspace. */@@ -44,12 +57,15 @@ const {failure?: string | null/** The link of the invitation just sent, for when the server sends no email. */invitationLink?: string | null+ /** The invitation just sent again, with the new link for when the server sends no email. */+ resent?: { invitationId: string; link: string } | null}>()const open = defineModel<boolean>('open', { default: false })const emit = defineEmits<{rename: [name: string]invite: [email: string, role: WorkspaceRole]+ resend: [invitationId: string]revoke: [invitationId: string]changeRole: [userId: string, role: WorkspaceRole]remove: [userId: string]@@ -61,9 +77,12 @@ const ui = cloudWorkspace()const { copy, copied } = useClipboard({ copiedDuring: 1500 })const t = useCloudMessages()const common = useCommonMessages()+const dates = useDateFormat()+const tab = ref('members')const name = ref(workspaceName)const email = ref('')const role = ref<WorkspaceRole>('editor')+const search = ref('')watch(() => workspaceName,(next) => {@@ -71,17 +90,31 @@ watch(})watch(open, (isOpen) => {- if (isOpen) email.value = ''+ if (!isOpen) return+ email.value = ''+ search.value = ''+ tab.value = 'members'})const roleOptions = computed(() => [- { value: 'admin' as const, label: t.value.roleAdmin },- { value: 'editor' as const, label: t.value.roleEditor },- { value: 'viewer' as const, label: t.value.roleViewer }+ { value: 'admin' as const, label: t.value.roleAdmin, description: t.value.roleAdminDescription },+ {+ value: 'editor' as const,+ label: t.value.roleEditor,+ description: t.value.roleEditorDescription+ },+ {+ value: 'viewer' as const,+ label: t.value.roleViewer,+ description: t.value.roleViewerDescription+ }])+const roleDescriptions = computed<Record<string, string>>(() =>+ Object.fromEntries(roleOptions.value.map((option) => [option.value, option.description]))+)/** As in the Share dialog, removing someone is the last choice of their role menu. */const memberOptions = computed(() => [...roleOptions.value,- { value: 'remove' as const, label: t.value.shareRemoveAccess }+ { value: 'remove' as const, label: t.value.shareRemoveAccess, description: '' }])function changeMember(userId: string, name: string, next: WorkspaceRole | 'remove') {if (next === 'remove') confirming.value = { kind: 'remove', userId, name }@@ -94,6 +127,28 @@ const roleLabels = computed<Record<WorkspaceRole, string>>(() => ({}))const renamed = computed(() => name.value.trim() && name.value.trim() !== workspaceName)+const allMembers = computed(() => members?.members ?? [])+const invitations = computed(() => (canManage ? (members?.invitations ?? []) : []))+const shownMembers = computed(() => {+ const query = search.value.trim().toLowerCase()+ if (!query) return allMembers.value+ return allMembers.value.filter(+ (member) =>+ member.name.toLowerCase().includes(query) || member.email.toLowerCase().includes(query)+ )+})+function invitationDetail(invitation: WorkspaceMembers['invitations'][number]): string {+ const date = dates.format(invitation.invitedAt, 'day')+ const inviter = invitation.invitedBy.name+ const sent = inviter+ ? t.value.invitationSentBy({ date, name: inviter })+ : t.value.invitationSent({ date })+ const expires = t.value.shareInvitationExpires({+ date: dates.format(invitation.expiresAt, 'day')+ })+ return `${sent} · ${expires}`+}+/** Leaving or removing someone takes away access, so it is asked once more. */const confirming = ref<{ kind: 'leave' } | { kind: 'delete' } | { kind: 'remove'; userId: string; name: string } | null@@ -154,147 +209,222 @@ function invite() {/><AppDialogBody><div :class="ui.stack()">- <form- v-if="canManage"- :class="ui.section()"- novalidate- @submit.prevent="renamed && emit('rename', name.trim())"- >- <label for="cloud-workspace-name" :class="ui.sectionTitle()">{{ t.workspaceName }}</label>- <div :class="ui.inline()">- <AppInput- id="cloud-workspace-name"- v-model="name"- maxlength="100"- :disabled="busy"- :ui="{ root: 'flex-1' }"- />- <AppButton v-if="renamed" type="submit" variant="outline" :disabled="busy">- {{ t.renameWorkspace }}- </AppButton>- </div>- </form>-- <section v-if="canManage" :class="ui.section()">- <h3 :class="ui.sectionTitle()">{{ t.invitePeople }}</h3>- <form :class="ui.inline()" novalidate @submit.prevent="invite">- <label for="cloud-workspace-invite" class="sr-only">{{ t.inviteEmail }}</label>- <AppInput- id="cloud-workspace-invite"- v-model="email"- type="email"- autocomplete="off"- :placeholder="t.inviteEmailPlaceholder"- :disabled="busy"- :ui="{ root: 'flex-1' }"- />- <AppSelect- v-model="role"- :label="t.inviteRole"- :options="roleOptions"- :ui="{ trigger: ui.roleSelect() }"- />- <AppButton type="submit" variant="outline" :disabled="busy || !email.trim()">- {{ t.invite }}- </AppButton>- </form>- <div v-if="invitationLink" :class="ui.sent()">- <p :class="ui.note()">{{ t.invitationSentNote }}</p>- <AppButton class="self-start" size="sm" variant="outline" @click="copy(invitationLink)">- <template #leading>- <icon-lucide-check v-if="copied" class="size-3.5" />- <icon-lucide-link v-else class="size-3.5" />+ <AppAlert v-if="failure" tone="error" :heading="failure" />+ <AppTabsRoot v-model="tab">+ <AppTabsList :label="t.membersSections">+ <AppTabsTrigger value="members">+ {{ t.membersTab }}+ <template #trailing>+ <span class="text-muted tabular-nums">{{ allMembers.length }}</span>+ </template>+ </AppTabsTrigger>+ <AppTabsTrigger v-if="canManage" value="invited">+ {{ t.invitedTab }}+ <template v-if="invitations.length" #trailing>+ <span class="text-muted tabular-nums">{{ invitations.length }}</span></template>- {{ copied ? common.copied : t.copyInvitationLink }}- </AppButton>- </div>- </section>+ </AppTabsTrigger>+ <AppTabsTrigger value="settings">{{ t.settingsTab }}</AppTabsTrigger>+ </AppTabsList>- <AppAlert v-if="failure" tone="error" :heading="failure" />+ <AppTabsContent value="members" :class="[ui.stack(), 'pt-4']">+ <section v-if="canManage" :class="ui.section()">+ <h3 :class="ui.sectionTitle()">{{ t.invitePeople }}</h3>+ <form :class="ui.inline()" novalidate @submit.prevent="invite">+ <label for="cloud-workspace-invite" class="sr-only">{{ t.inviteEmail }}</label>+ <AppInput+ id="cloud-workspace-invite"+ v-model="email"+ type="email"+ autocomplete="off"+ :placeholder="t.inviteEmailPlaceholder"+ :disabled="busy"+ :ui="{ root: 'flex-1' }"+ />+ <AppSelect+ v-model="role"+ :label="t.inviteRole"+ :options="roleOptions"+ :ui="{ trigger: ui.roleSelect(), item: ui.roleItem() }"+ >+ <template #option="{ option }">+ <span class="flex flex-col">+ <span>{{ option.label }}</span>+ <span class="text-[11px] text-muted">{{+ roleDescriptions[option.value]+ }}</span>+ </span>+ </template>+ </AppSelect>+ <AppButton type="submit" variant="outline" :disabled="busy || !email.trim()">+ {{ t.invite }}+ </AppButton>+ </form>+ <div v-if="invitationLink" :class="ui.sent()">+ <p :class="ui.note()">{{ t.invitationSentNote }}</p>+ <AppButton+ class="self-start"+ size="sm"+ variant="outline"+ @click="copy(invitationLink)"+ >+ <template #leading>+ <icon-lucide-check v-if="copied" class="size-3.5" />+ <icon-lucide-link v-else class="size-3.5" />+ </template>+ {{ copied ? common.copied : t.copyInvitationLink }}+ </AppButton>+ </div>+ </section>++ <section :class="ui.section()">+ <AppInput+ v-if="allMembers.length > MEMBER_SEARCH_THRESHOLD"+ v-model="search"+ type="search"+ density="compact"+ :placeholder="t.searchMembers"+ :aria-label="t.searchMembers"+ >+ <template #leading><icon-lucide-search class="size-3.5" /></template>+ </AppInput>+ <p v-if="loading" :class="ui.note()" role="status">{{ t.membersLoading }}</p>+ <p v-else-if="search.trim() && shownMembers.length === 0" :class="ui.note()">+ {{ t.noMembersMatch }}+ </p>+ <ul v-else :class="ui.list()">+ <li v-for="member in shownMembers" :key="member.userId" :class="ui.row()">+ <AccountAvatar :id="member.userId" :name="member.name" :image="member.image" />+ <span :class="ui.person()">+ <span :class="ui.personName()">+ {{ member.name }}+ <span v-if="member.userId === self" :class="ui.you()">{{ common.you }}</span>+ </span>+ <span :class="ui.personEmail()">+ {{ member.email }} ·+ {{ t.memberJoined({ date: dates.format(member.joinedAt, 'date') }) }}+ </span>+ </span>+ <AppSelect+ v-if="canManage"+ :model-value="member.role"+ :label="t.memberRole({ name: member.name })"+ :options="member.userId === self ? roleOptions : memberOptions"+ :disabled="busy"+ :ui="{ trigger: ui.roleSelect() }"+ @update:model-value="(next) => changeMember(member.userId, member.name, next)"+ />+ <span v-else :class="ui.role()">{{ roleLabels[member.role] }}</span>+ </li>+ </ul>+ </section>+ </AppTabsContent>- <section :class="ui.section()">- <h3 :class="ui.sectionTitle()">- {{ t.shareMemberCount(members?.members.length ?? 0) }}- </h3>- <p v-if="loading" :class="ui.note()" role="status">{{ t.membersLoading }}</p>- <ul v-else :class="ui.list()">- <li v-for="member in members?.members ?? []" :key="member.userId" :class="ui.row()">- <AccountAvatar :id="member.userId" :name="member.name" />- <span :class="ui.person()">- <span :class="ui.personName()">- {{ member.name }}- <span v-if="member.userId === self" :class="ui.you()">{{ common.you }}</span>+ <AppTabsContent v-if="canManage" value="invited" :class="[ui.stack(), 'pt-4']">+ <ul v-if="invitations.length" :class="ui.list()">+ <li v-for="invitation in invitations" :key="invitation.id" :class="ui.row()">+ <span :class="ui.pendingIcon()"><icon-lucide-mail class="size-3.5" /></span>+ <span :class="ui.person()">+ <span :class="ui.personName()">{{ invitation.email }}</span>+ <span :class="ui.personDetail()">{{ invitationDetail(invitation) }}</span></span>- <span :class="ui.personEmail()">{{ member.email }}</span>- </span>- <AppSelect- v-if="canManage"- :model-value="member.role"- :label="t.memberRole({ name: member.name })"- :options="member.userId === self ? roleOptions : memberOptions"- :disabled="busy"- :ui="{ trigger: ui.roleSelect() }"- @update:model-value="(next) => changeMember(member.userId, member.name, next)"- />- <span v-else :class="ui.role()">{{ roleLabels[member.role] }}</span>- </li>- </ul>- </section>+ <span :class="ui.role()">{{ roleLabels[invitation.role] }}</span>+ <template v-if="resent?.invitationId === invitation.id">+ <AppBadge>{{ t.invitationResent }}</AppBadge>+ <IconButton :label="t.copyInvitationLink" @click="copy(resent.link)">+ <icon-lucide-check v-if="copied" class="size-3.5" />+ <icon-lucide-link v-else class="size-3.5" />+ </IconButton>+ </template>+ <AppButton+ v-else+ size="xs"+ variant="link"+ :disabled="busy"+ @click="emit('resend', invitation.id)"+ >+ {{ t.resendInvitation }}+ </AppButton>+ <AppButton+ size="xs"+ variant="link"+ :disabled="busy"+ @click="emit('revoke', invitation.id)"+ >+ {{ t.revokeInvitation }}+ </AppButton>+ </li>+ </ul>+ <AppPlaceholder+ v-else+ size="compact"+ :fill="false"+ :label="t.noInvitations"+ :description="t.noInvitationsDescription"+ >+ <template #icon><icon-lucide-mail class="size-5" /></template>+ </AppPlaceholder>+ </AppTabsContent>- <section v-if="canManage && members?.invitations.length" :class="ui.section()">- <h3 :class="ui.sectionTitle()">{{ t.pendingInvitations }}</h3>- <ul :class="ui.list()">- <li v-for="invitation in members.invitations" :key="invitation.id" :class="ui.row()">- <span :class="ui.pendingIcon()"><icon-lucide-mail class="size-3.5" /></span>- <span :class="ui.person()">- <span :class="ui.personName()">{{ invitation.email }}</span>- </span>- <span :class="ui.role()">{{ roleLabels[invitation.role] }}</span>- <AppButton- size="xs"- variant="link"- :disabled="busy"- @click="emit('revoke', invitation.id)"- >- {{ t.revokeInvitation }}- </AppButton>- </li>- </ul>- </section>+ <AppTabsContent value="settings" :class="[ui.stack(), 'pt-4']">+ <form+ v-if="canManage"+ :class="ui.section()"+ novalidate+ @submit.prevent="renamed && emit('rename', name.trim())"+ >+ <label for="cloud-workspace-name" :class="ui.sectionTitle()">{{+ t.workspaceName+ }}</label>+ <div :class="ui.inline()">+ <AppInput+ id="cloud-workspace-name"+ v-model="name"+ maxlength="100"+ :disabled="busy"+ :ui="{ root: 'flex-1' }"+ />+ <AppButton v-if="renamed" type="submit" variant="outline" :disabled="busy">+ {{ t.renameWorkspace }}+ </AppButton>+ </div>+ </form>- <section :class="ui.section()" aria-labelledby="cloud-workspace-danger">- <h3 id="cloud-workspace-danger" :class="ui.dangerTitle()">{{ t.dangerZone }}</h3>- <ul :class="ui.dangerList()">- <li :class="ui.dangerRow()">- <span :class="ui.person()">- <span :class="ui.personName()">{{ t.leaveWorkspace }}</span>- <span :class="ui.dangerDescription()">{{ t.leaveWorkspaceDescription }}</span>- </span>- <AppButton- color="error"- variant="outline"- :disabled="busy"- @click="confirming = { kind: 'leave' }"- >- {{ t.leaveWorkspaceShort }}- </AppButton>- </li>- <li v-if="canManage" :class="ui.dangerRow()">- <span :class="ui.person()">- <span :class="ui.personName()">{{ t.deleteWorkspace }}</span>- <span :class="ui.dangerDescription()">{{ t.deleteWorkspaceDescription }}</span>- </span>- <AppButton- color="error"- variant="outline"- :disabled="busy"- @click="confirming = { kind: 'delete' }"- >- {{ t.deleteWorkspaceShort }}- </AppButton>- </li>- </ul>- </section>+ <section :class="ui.section()" aria-labelledby="cloud-workspace-danger">+ <h3 id="cloud-workspace-danger" :class="ui.dangerTitle()">{{ t.dangerZone }}</h3>+ <ul :class="ui.dangerList()">+ <li :class="ui.dangerRow()">+ <span :class="ui.person()">+ <span :class="ui.personName()">{{ t.leaveWorkspace }}</span>+ <span :class="ui.dangerDescription()">{{ t.leaveWorkspaceDescription }}</span>+ </span>+ <AppButton+ color="error"+ variant="outline"+ :disabled="busy"+ @click="confirming = { kind: 'leave' }"+ >+ {{ t.leaveWorkspaceShort }}+ </AppButton>+ </li>+ <li v-if="canManage" :class="ui.dangerRow()">+ <span :class="ui.person()">+ <span :class="ui.personName()">{{ t.deleteWorkspace }}</span>+ <span :class="ui.dangerDescription()">{{ t.deleteWorkspaceDescription }}</span>+ </span>+ <AppButton+ color="error"+ variant="outline"+ :disabled="busy"+ @click="confirming = { kind: 'delete' }"+ >+ {{ t.deleteWorkspaceShort }}+ </AppButton>+ </li>+ </ul>+ </section>+ </AppTabsContent>+ </AppTabsRoot></div></AppDialogBody><AppDialogFooter>diff --git a/src/components/cloud/workspace/CloudWorkspaceMembersHost.vue b/src/components/cloud/workspace/CloudWorkspaceMembersHost.vueindex f5bdb32ab..d7c9b3fd9 100644--- a/src/components/cloud/workspace/CloudWorkspaceMembersHost.vue+++ b/src/components/cloud/workspace/CloudWorkspaceMembersHost.vue@@ -7,7 +7,8 @@ import {changeWorkspaceRole,deleteWorkspace,inviteToWorkspace,- lastInvitationLink,+ lastInvitation,+ lastResent,leaveWorkspace,membersBusy,membersFailure,@@ -17,6 +18,7 @@ import {membersWorkspace,removeWorkspaceMember,renameWorkspace,+ resendWorkspaceInvitation,revokeWorkspaceInvitation,workspaceMembers,type WorkspaceFailure@@ -53,10 +55,12 @@ const failure = computed(() => {:loading="membersLoading":busy="membersBusy":failure="failure"- :invitation-link="lastInvitationLink"+ :invitation-link="lastInvitation?.link ?? null"+ :resent="lastResent"@rename="renameWorkspace"@invite="inviteToWorkspace"@revoke="revokeWorkspaceInvitation"+ @resend="resendWorkspaceInvitation"@change-role="changeWorkspaceRole"@remove="removeWorkspaceMember"@leave="leaveWorkspace"diff --git a/src/components/home/HomeLayout.vue b/src/components/home/HomeLayout.vueindex 5838e6ae0..e9d1a0d60 100644--- a/src/components/home/HomeLayout.vue+++ b/src/components/home/HomeLayout.vue@@ -11,7 +11,7 @@<slot name="sidebar" /></div><main class="flex min-h-0 min-w-0 flex-1 flex-col overflow-x-hidden overflow-y-auto">- <div class="mx-auto flex w-full max-w-6xl flex-col px-4 py-4 sm:px-6 sm:py-5">+ <div class="flex w-full flex-col px-4 py-4 sm:px-6 sm:py-5"><div v-if="$slots.locations" class="mb-3 md:hidden"><slot name="locations" /></div><slot /></div>diff --git a/src/components/home/sidebar/HomeSidebar.vue b/src/components/home/sidebar/HomeSidebar.vueindex e45b5b8e9..bfc61edb3 100644--- a/src/components/home/sidebar/HomeSidebar.vue+++ b/src/components/home/sidebar/HomeSidebar.vue@@ -66,7 +66,7 @@ const workspaceLocations = computed(() =><template><nav :class="ui.root()" :aria-label="t.homeLocations">- <div :class="[ui.items(), 'pt-1']">+ <div :class="ui.group()"><buttontype="button":class="ui.item()"diff --git a/src/components/presence/AccountAvatar.vue b/src/components/presence/AccountAvatar.vueindex 5d7aac6f6..9184a1ba3 100644--- a/src/components/presence/AccountAvatar.vue+++ b/src/components/presence/AccountAvatar.vue@@ -1,19 +1,43 @@<script setup lang="ts">-import { computed } from 'vue'+import { computed, ref, watch } from 'vue'import PersonAvatar from '@/components/presence/PersonAvatar.vue'import { PEER_COLORS } from '@/constants'+import { avatar } from '@/theme/collaboration/avatar/person'-/** An account's initials on a color that stays the same for that account. */-const { id, name, size = 'sm' } = defineProps<{ id: string; name: string; size?: 'sm' | 'md' }>()+/**+ * An account's picture, such as one its sign-in provider gave it, or else its initials on a color+ * that stays the same for that account. A picture that fails to load falls back to the initials.+ */+const {+ id,+ name,+ image = null,+ size = 'sm'+} = defineProps<{ id: string; name: string; image?: string | null; size?: 'sm' | 'md' | 'lg' }>()const color = computed(() => {let hash = 0for (const character of id) hash = (hash * 31 + (character.codePointAt(0) ?? 0)) >>> 0return PEER_COLORS[hash % PEER_COLORS.length] ?? PEER_COLORS[0]})+const failed = ref(false)+watch(+ () => image,+ () => {+ failed.value = false+ }+)</script><template>- <PersonAvatar :name="name" :color="color" :size="size" />+ <img+ v-if="image && !failed"+ :src="image"+ alt=""+ referrerpolicy="no-referrer"+ :class="avatar({ size, bordered: true, class: 'object-cover' })"+ @error="failed = true"+ />+ <PersonAvatar v-else :name="name" :color="color" :size="size" /></template>diff --git a/src/components/presence/PersonAvatar.vue b/src/components/presence/PersonAvatar.vueindex de683bc84..39ea78e23 100644--- a/src/components/presence/PersonAvatar.vue+++ b/src/components/presence/PersonAvatar.vue@@ -24,7 +24,7 @@ const {name: stringcolor: ColoragentCount?: number- size?: 'sm' | 'md'+ size?: 'sm' | 'md' | 'lg'following?: booleaninteractive?: booleanvoice?: PresenceVoicediff --git a/src/theme/cloud-portal/layout.ts b/src/theme/cloud-portal/layout.tsindex 6571d5e4d..b7939e8fd 100644--- a/src/theme/cloud-portal/layout.ts+++ b/src/theme/cloud-portal/layout.ts@@ -12,13 +12,13 @@ export const portalLayout = tv({barEnd: 'ml-auto flex items-center gap-2',console: 'flex min-h-0 flex-1 max-md:flex-col',// Narrow screens turn the section list into one scrolling row above the page.- nav: 'max-md:h-auto max-md:w-full max-md:flex-row max-md:overflow-x-auto max-md:border-r-0 max-md:border-b max-md:pb-0',- navGroup: 'max-md:flex-row max-md:items-center',+ nav: 'max-md:h-auto max-md:w-full max-md:flex-row max-md:overflow-x-auto max-md:border-r-0 max-md:border-b max-md:p-1',+ navGroup: 'max-md:flex-row max-md:items-center max-md:border-t-0 max-md:p-0',navHeader: 'max-md:hidden',- navItems: 'max-md:flex-row max-md:p-1',+ navItems: 'max-md:flex-row',navItem: 'max-md:w-auto max-md:shrink-0',main: 'min-w-0 flex-1 overflow-y-auto',- mainInner: 'mx-auto flex w-full max-w-5xl flex-col gap-5 px-4 py-6 md:px-6',+ mainInner: 'flex w-full max-w-5xl flex-col gap-5 px-4 py-6 md:px-6',pageTitle: 'text-base font-semibold',pageDescription: 'mt-0.5 text-xs text-muted'}diff --git a/src/theme/cloud/workspace.ts b/src/theme/cloud/workspace.tsindex 1d2c86be8..e4d3ca6c8 100644--- a/src/theme/cloud/workspace.ts+++ b/src/theme/cloud/workspace.ts@@ -16,9 +16,12 @@ export const cloudWorkspace = tv({person: 'flex min-w-0 flex-1 flex-col',personName: 'truncate text-xs text-surface',personEmail: 'truncate text-[11px] text-muted',+ personDetail: 'text-[11px] text-pretty text-muted',you: 'ml-1 text-[11px] text-muted',role: 'shrink-0 text-[11px] text-muted',roleSelect: 'w-28 shrink-0',+ /** A role in the invite menu, with what it lets someone do on a second line. */+ roleItem: 'h-auto max-w-80 py-1',dangerTitle: 'text-[11px] font-medium text-error',dangerList: 'flex flex-col divide-y divide-error-border rounded border border-error-border',dangerRow: 'flex items-center gap-3 px-3 py-2.5',diff --git a/src/theme/collaboration/avatar/person.ts b/src/theme/collaboration/avatar/person.tsindex bc118659b..4a7fe2c8c 100644--- a/src/theme/collaboration/avatar/person.ts+++ b/src/theme/collaboration/avatar/person.ts@@ -4,7 +4,7 @@ import { tv } from 'tailwind-variants'export const avatar = tv({base: 'flex shrink-0 items-center justify-center rounded-full text-[10px] font-semibold text-white',variants: {- size: { sm: 'size-6', md: 'size-7' },+ size: { sm: 'size-6', md: 'size-7', lg: 'size-12 text-base' },bordered: { true: 'border-2 border-panel', false: '' },following: { true: 'ring-2 ring-white/40', false: '' },/** A collaborator's avatar, which follows them when clicked. */diff --git a/src/theme/list/side-list.ts b/src/theme/list/side-list.tsindex 263d04ad9..fe81aa74a 100644--- a/src/theme/list/side-list.ts+++ b/src/theme/list/side-list.ts@@ -1,18 +1,18 @@import { tv } from 'tailwind-variants'-/** A side list of places, drawn like the editor's Pages panel: headings, 24px rows, hover selection. */+/** A side list of places, drawn like the Settings dialog's sections: groups split by rules, headings, 28px rows with icons. */export const sideList = tv({slots: {- root: 'flex h-full w-60 shrink-0 flex-col overflow-y-auto border-r border-border bg-panel pb-2',- group: 'flex flex-col',- header: 'flex h-8 shrink-0 items-center justify-between pr-1.5 pl-3',- title: 'text-[11px] font-semibold text-surface',+ root: 'flex h-full w-64 shrink-0 flex-col overflow-y-auto border-r border-border bg-panel',+ group: 'flex flex-col gap-0.5 border-t border-border p-2 first:border-t-0',+ header: 'flex h-7 shrink-0 items-center justify-between pr-0.5 pl-2',+ title: 'text-[11px] font-semibold text-muted',actions: 'flex items-center gap-0.5',- items: 'flex flex-col px-1 pb-1',- item: 'group flex h-6 w-full cursor-pointer items-center gap-1.5 rounded border-none bg-transparent px-2 text-left text-[11px] text-muted outline-none hover:bg-hover hover:text-surface focus-visible:ring-1 focus-visible:ring-panel-focus data-[active=true]:bg-hover data-[active=true]:text-surface',- icon: 'size-3 shrink-0 opacity-70',+ items: 'flex flex-col gap-0.5',+ item: 'group flex h-7 w-full shrink-0 cursor-pointer items-center gap-2 rounded border-none bg-transparent px-2 text-left text-xs text-muted outline-none transition-colors hover:bg-hover hover:text-surface focus-visible:ring-2 focus-visible:ring-accent/50 data-[active=true]:bg-hover data-[active=true]:text-surface',+ icon: 'size-3.5 shrink-0',label: 'min-w-0 flex-1 truncate',- trailing: 'flex shrink-0 items-center gap-1.5 text-[10px] text-muted tabular-nums',- attention: 'size-3 text-warning'+ trailing: 'flex shrink-0 items-center gap-1.5 text-[11px] text-muted tabular-nums',+ attention: 'size-3.5 text-warning'}})diff --git a/src/views/cloud/ConsoleView.vue b/src/views/cloud/ConsoleView.vueindex d15930123..1de6166cb 100644--- a/src/views/cloud/ConsoleView.vue+++ b/src/views/cloud/ConsoleView.vue@@ -6,17 +6,27 @@ import { useCloudPortalMessages } from '@open-pencil/vue/i18n'import { usePortal } from '@/app/cloud-portal/context'import PortalConsoleLayout from '@/components/cloud-portal/layout/PortalConsoleLayout.vue'+import { PORTAL_SECTION_ICONS } from '@/components/cloud-portal/layout/sections'import AdminActivitySection from '@/components/cloud-portal/sections/AdminActivitySection.vue'import AdminEmailSection from '@/components/cloud-portal/sections/AdminEmailSection.vue'import AdminOverviewSection from '@/components/cloud-portal/sections/AdminOverviewSection.vue'import AdminPeopleSection from '@/components/cloud-portal/sections/AdminPeopleSection.vue'+import AdminPersonSection from '@/components/cloud-portal/sections/AdminPersonSection.vue'import AdminRequestsSection from '@/components/cloud-portal/sections/AdminRequestsSection.vue'+import ProfileSection from '@/components/cloud-portal/sections/ProfileSection.vue'import SecuritySection from '@/components/cloud-portal/sections/SecuritySection.vue'+import SessionsSection from '@/components/cloud-portal/sections/SessionsSection.vue'import type { PortalSection } from '@/components/cloud-portal/types'+const ACCOUNT_SECTIONS = ['profile', 'security', 'sessions'] as constconst ADMIN_SECTIONS = ['overview', 'requests', 'people', 'email', 'activity'] as const+type AccountSectionId = (typeof ACCOUNT_SECTIONS)[number]type AdminSectionId = (typeof ADMIN_SECTIONS)[number]-type SectionId = 'security' | AdminSectionId+type SectionId = AccountSectionId | AdminSectionId++function isAccountSection(value: unknown): value is AccountSectionId {+ return ACCOUNT_SECTIONS.some((section) => section === value)+}function isAdminSection(value: unknown): value is AdminSectionId {return ADMIN_SECTIONS.some((section) => section === value)@@ -30,36 +40,85 @@ const waiting = ref(0)const peopleTotal = ref<number | null>(null)const admin = computed(() => portal.account.value?.user.deploymentRole === 'admin')+/** The account an administrator opened from People, when the page shows one. */+const personId = computed(() => {+ const value = route.params.userId+ return route.name === 'person' && typeof value === 'string' ? value : null+})const active = computed<SectionId>(() => {- if (route.name !== 'admin') return 'security'+ if (isAccountSection(route.name)) return route.name+ if (personId.value) return 'people'const section = route.params.sectionreturn isAdminSection(section) ? section : 'overview'})const sections = computed<PortalSection[]>(() => {const value = messages.value- const account = [{ id: 'security', label: value.security, group: value.sectionAccount }]+ const account: PortalSection[] = [+ {+ id: 'profile',+ icon: PORTAL_SECTION_ICONS.profile,+ label: value.profile,+ group: value.sectionAccount+ },+ {+ id: 'security',+ icon: PORTAL_SECTION_ICONS.security,+ label: value.security,+ group: value.sectionAccount+ },+ {+ id: 'sessions',+ icon: PORTAL_SECTION_ICONS.sessions,+ label: value.sessions,+ group: value.sectionAccount+ }+ ]if (!admin.value) return accountreturn [...account,- { id: 'overview', label: value.overview, group: value.sectionServer },+ {+ id: 'overview',+ icon: PORTAL_SECTION_ICONS.overview,+ label: value.overview,+ group: value.sectionServer+ },{id: 'requests',+ icon: PORTAL_SECTION_ICONS.requests,label: value.accessRequests,group: value.sectionServer,count: waiting.value || undefined},- { id: 'people', label: value.people, group: value.sectionServer },- { id: 'email', label: value.emailDelivery, group: value.sectionServer },- { id: 'activity', label: value.activity, group: value.sectionServer }+ {+ id: 'people',+ icon: PORTAL_SECTION_ICONS.people,+ label: value.people,+ group: value.sectionServer+ },+ {+ id: 'email',+ icon: PORTAL_SECTION_ICONS.email,+ label: value.emailDelivery,+ group: value.sectionServer+ },+ {+ id: 'activity',+ icon: PORTAL_SECTION_ICONS.activity,+ label: value.activity,+ group: value.sectionServer+ }]})const heading = computed(() => sections.value.find((section) => section.id === active.value)?.label ?? '')const description = computed(() => {+ if (personId.value) return ''const value = messages.valueconst descriptions: Record<SectionId, string> = {+ profile: value.profileDescription({ host: portal.host }),security: value.securityDescription({ host: portal.host }),+ sessions: value.sessionsDescription,overview: portal.host,requests: value.accessRequestsDescription,people: peopleTotal.value === null ? '' : value.peopleDescription(peopleTotal.value),@@ -77,10 +136,14 @@ async function refreshWaiting() {}function select(id: string) {- if (id === 'security') void router.push({ name: 'security' })+ if (isAccountSection(id)) void router.push({ name: id })else void router.push({ name: 'admin', params: { section: id === 'overview' ? '' : id } })}+function openPerson(userId: string) {+ void router.push({ name: 'person', params: { userId } })+}+async function signOut() {await portal.auth.signOut()await portal.refreshAccount()@@ -97,7 +160,8 @@ onMounted(() => void refreshWaiting()):account="{id: portal.account.value.user.userId,name: portal.account.value.user.name,- email: portal.account.value.user.email+ email: portal.account.value.user.email,+ image: portal.account.value.user.image ?? null}":sections="sections":active="active"@@ -106,10 +170,17 @@ onMounted(() => void refreshWaiting())@select="select"@sign-out="signOut">- <SecuritySection v-if="active === 'security'" />+ <ProfileSection v-if="active === 'profile'" />+ <SecuritySection v-else-if="active === 'security'" />+ <SessionsSection v-else-if="active === 'sessions'" /><AdminOverviewSection v-else-if="active === 'overview'" @open="select" /><AdminRequestsSection v-else-if="active === 'requests'" @changed="refreshWaiting" />- <AdminPeopleSection v-else-if="active === 'people'" @total="(count) => (peopleTotal = count)" />+ <AdminPersonSection v-else-if="personId" :user-id="personId" @back="select('people')" />+ <AdminPeopleSection+ v-else-if="active === 'people'"+ @total="(count) => (peopleTotal = count)"+ @open="openPerson"+ /><AdminEmailSection v-else-if="active === 'email'" /><AdminActivitySection v-else /></PortalConsoleLayout>diff --git a/tests/integration/cloud/service-worker.test.ts b/tests/integration/cloud/service-worker.test.tsindex 25abf75f6..4087fc923 100644--- a/tests/integration/cloud/service-worker.test.ts+++ b/tests/integration/cloud/service-worker.test.ts@@ -10,6 +10,8 @@ describe('editor service worker on a Cloud server', () => {for (const root of CLOUD_PORTAL_PAGE_ROOTS) {expect(servedByEditor(root)).toBe(false)expect(servedByEditor(`${root}/x`)).toBe(false)+ // Workbox matches the path with its query, as a confirmation link that returns arrives.+ expect(servedByEditor(`${root}?confirmed`)).toBe(false)}expect(servedByEditor('/api/account/status')).toBe(false)expect(servedByEditor('/.well-known/openpencil')).toBe(false)@@ -22,7 +24,9 @@ describe('editor service worker on a Cloud server', () => {'/rooms/abc','/documents/abc','/share/abc',- '/invitations/abc'+ '/invitations/abc',+ '/accounts',+ '/?welcome']) {expect(servedByEditor(path)).toBe(true)}diff --git a/tools/checks/i18n/mixed-script-baseline.txt b/tools/checks/i18n/mixed-script-baseline.txtindex 4e821b63e..c00cd97de 100644--- a/tools/checks/i18n/mixed-script-baseline.txt+++ b/tools/checks/i18n/mixed-script-baseline.txt@@ -520,6 +520,9 @@ ja:cloud.settingsSelfHostedDescriptionja:cloudPortal.errorEmailInvalidja:cloudPortal.verifiedDescriptionja:cloudPortal.welcomeTitle+ja:cloudPortal.accountId+ja:cloudPortal.desktopApp+ja:cloudPortal.methodDesktopzh-cn:cloud.connectHeadingzh-cn:cloud.connectServerDescriptionzh-cn:cloud.officialDescription@@ -537,6 +540,10 @@ zh-cn:cloud.settingsSelfHostedDescriptionzh-cn:cloudPortal.errorEmailInvalidzh-cn:cloudPortal.verifiedDescriptionzh-cn:cloudPortal.welcomeTitle+zh-cn:cloudPortal.accountId+zh-cn:cloudPortal.accountIdDescription+zh-cn:cloudPortal.desktopApp+zh-cn:cloudPortal.methodDesktopja:ai.cloudAIUnavailableja:ai.cloudAINoWorkspaceja:ai.chatCloudCreditsExhausteddiff --git a/tools/checks/i18n/translation-baseline.txt b/tools/checks/i18n/translation-baseline.txtindex d4cea9792..4ce61e519 100644--- a/tools/checks/i18n/translation-baseline.txt+++ b/tools/checks/i18n/translation-baseline.txt@@ -381,6 +381,9 @@ pl:statuses.statuses:cloudPortal.productNamees:cloudPortal.providerGooglees:cloudPortal.providerApple+es:cloudPortal.methodGoogle+es:cloudPortal.methodApple+es:cloudPortal.workspaceRoleEditores:cloudPortal.deploymentOfficiales:cloudPortal.emailTransportSMTPes:cloudPortal.emailTransportCloudflare@@ -390,6 +393,11 @@ it:cloudPortal.passwordit:cloudPortal.sectionServerit:cloudPortal.providerGoogleit:cloudPortal.providerApple+it:cloudPortal.methodGoogle+it:cloudPortal.methodApple+it:cloudPortal.methodPassword+it:cloudPortal.personAccount+it:cloudPortal.workspaceRoleEditorit:cloudPortal.unnamedPasskeyit:cloudPortal.serverSectionit:cloudPortal.deploymentOfficial@@ -402,6 +410,8 @@ de:cloudPortal.namede:cloudPortal.sectionServerde:cloudPortal.providerGooglede:cloudPortal.providerApple+de:cloudPortal.methodGoogle+de:cloudPortal.methodApplede:cloudPortal.passkeysde:cloudPortal.unnamedPasskeyde:cloudPortal.administrator@@ -412,6 +422,9 @@ de:cloudPortal.emailTransportCloudflarefr:cloudPortal.productNamefr:cloudPortal.providerGooglefr:cloudPortal.providerApple+fr:cloudPortal.sessions+fr:cloudPortal.personSessions+fr:cloudPortal.documentsfr:cloudPortal.deploymentOfficialfr:cloudPortal.emailTransportSMTPfr:cloudPortal.emailTransportCloudflare@@ -419,6 +432,8 @@ ja:cloudPortal.productNameja:cloudPortal.emailPlaceholderja:cloudPortal.providerGoogleja:cloudPortal.providerApple+ja:cloudPortal.methodGoogle+ja:cloudPortal.methodAppleja:cloudPortal.deploymentOfficialja:cloudPortal.emailTransportSMTPja:cloudPortal.emailTransportCloudflare@@ -426,6 +441,8 @@ zh-cn:cloudPortal.productNamezh-cn:cloudPortal.emailPlaceholderzh-cn:cloudPortal.providerGooglezh-cn:cloudPortal.providerApple+zh-cn:cloudPortal.methodGoogle+zh-cn:cloudPortal.methodApplezh-cn:cloudPortal.deploymentOfficialzh-cn:cloudPortal.emailTransportSMTPzh-cn:cloudPortal.emailTransportCloudflare@@ -433,6 +450,8 @@ pl:cloudPortal.productNamepl:cloudPortal.emailPlaceholderpl:cloudPortal.providerGooglepl:cloudPortal.providerApple+pl:cloudPortal.methodGoogle+pl:cloudPortal.methodApplepl:cloudPortal.administratorpl:cloudPortal.deploymentOfficialpl:cloudPortal.emailTransportSMTP@@ -441,6 +460,8 @@ ru:cloudPortal.productNameru:cloudPortal.emailPlaceholderru:cloudPortal.providerGoogleru:cloudPortal.providerApple+ru:cloudPortal.methodGoogle+ru:cloudPortal.methodAppleru:cloudPortal.deploymentOfficialru:cloudPortal.emailTransportSMTPru:cloudPortal.emailTransportCloudflarediff --git a/vite/pwa.ts b/vite/pwa.tsindex 5fbdbf100..4fd879b5c 100644--- a/vite/pwa.ts+++ b/vite/pwa.ts@@ -3,13 +3,14 @@ import { VitePWA } from 'vite-plugin-pwa'/*** Pages that are not the editor's: OAuth callbacks, which relay a redirect, and, where a Cloud* server serves the editor, its API and its own pages, `CLOUD_PORTAL_PAGE_ROOTS` in- * `@open-pencil/cloud/contract`, which loads only once packages are built.+ * `@open-pencil/cloud/contract`, which loads only once packages are built. Workbox matches the+ * path with its query, so a page root may be followed by `?` as well as `/`.*/export const NOT_EDITOR_PAGES = [/^\/oauth\//,/^\/api\//,/^\/\.well-known\//,- /^\/(?:welcome|auth|account|admin)(?:\/|$)/+ /^\/(?:welcome|auth|account|admin)(?:[/?]|$)/]export function openPencilPwaPlugin() {