diff --git a/frontend/index.html b/frontend/index.html index c0278e9..6dd149a 100644 --- a/frontend/index.html +++ b/frontend/index.html @@ -6,10 +6,19 @@ Tranquil PDS - + diff --git a/frontend/mockups/01-article-style.html b/frontend/mockups/01-article-style.html deleted file mode 100644 index 42a9bbf..0000000 --- a/frontend/mockups/01-article-style.html +++ /dev/null @@ -1,650 +0,0 @@ - - - - - - Tranquil - - - - - - - -
-
-
-
- - - -
-
-
- Landing page - 1 min read -
- -

Lorem Ipsum Dolor Sit Amet Consectetur

- - - -
-
-

"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."

- Cicero, De Finibus Bonorum et Malorum -
- -

Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit.

- -

Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo.

- -

Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt.

- -

Neque Porro Quisquam

- -

Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

- -

Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur.

- -

Quis Autem Vel Eum

- -

Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur.

- -

At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident.

- -

Similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio.

- -

Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus.

- -

Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae.

- - -
- - -
-
- - - - - - diff --git a/frontend/mockups/02-normal-colors.html b/frontend/mockups/02-normal-colors.html deleted file mode 100644 index 5c7668a..0000000 --- a/frontend/mockups/02-normal-colors.html +++ /dev/null @@ -1,679 +0,0 @@ - - - - - - Tranquil - - - - - - - -
-
-
-
- - - -
-
-
- Landing page - 1 min read -
- -

Lorem Ipsum Dolor Sit Amet Consectetur

- - - -
-
-

"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."

- Cicero, De Finibus Bonorum et Malorum -
- -

Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit.

- -

Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo.

- -

Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt.

- -

Neque Porro Quisquam

- -

Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

- -

Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur.

- -

Quis Autem Vel Eum

- -

Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur.

- -

At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident.

- -

Similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio.

- -

Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus.

- -

Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae.

- - -
- - -
-
- - - - - - diff --git a/frontend/mockups/03-landing-page.html b/frontend/mockups/03-landing-page.html deleted file mode 100644 index cfb9d72..0000000 --- a/frontend/mockups/03-landing-page.html +++ /dev/null @@ -1,714 +0,0 @@ - - - - - - Tranquil - - - - - - - -
-
-
-
- - - -
-
-

A home for your ATProto account

- -

Tranquil PDS is a Personal Data Server, the thing that stores your posts, profile, and keys. Bluesky runs one for you, but you can run your own.

- -
- - -
-
-

"Nature does not hurry, yet everything is accomplished."

- Lao Tzu -
-
- -
-

What you get

- -
-
-

Real security

-

Sign in with passkeys, add two-factor authentication, set up backup codes, and mark devices you trust. Your account stays yours.

-
- -
-

Your own identity

-

Use your own domain as your handle, or get a subdomain on ours. Either way, your identity moves with you if you ever leave.

-
- -
-

Stay in the loop

-

Get important alerts where you actually see them: email, Discord, Telegram, or Signal.

-
- -
-

You decide what apps can do

-

When an app asks for access, you'll see exactly what it wants in plain language. Grant what makes sense, deny what doesn't.

-
-
- -

Everything in one place

- -

Manage your profile, security settings, connected apps, and more from a clean dashboard. No command line or 3rd party apps required.

- - - -

Works with everything

- -

Use any ATProto app you already like. Tranquil PDS speaks the same language as Bluesky's servers, so all your favorite clients, tools, and bots just work.

- -

Ready to try it?

- -

Join this server, or grab the source and run your own. Either way, you can migrate an existing account over and your followers, posts, and identity come with you.

- -
- - -
-
-
- - - - - - diff --git a/frontend/src/components/ui/Page.svelte b/frontend/src/components/ui/Page.svelte index 2fcfed1..7d2d94b 100644 --- a/frontend/src/components/ui/Page.svelte +++ b/frontend/src/components/ui/Page.svelte @@ -44,9 +44,9 @@ padding: var(--space-7); } - .page-sm { max-width: var(--width-sm); } - .page-md { max-width: var(--width-md); } - .page-lg { max-width: var(--width-lg); } + .page-sm { max-width: var(--width-md); } + .page-md { max-width: var(--width-lg); } + .page-lg { max-width: var(--width-xl); } header { margin-bottom: var(--space-7); diff --git a/frontend/src/components/ui/index.ts b/frontend/src/components/ui/index.ts index 083a3ce..f2f3068 100644 --- a/frontend/src/components/ui/index.ts +++ b/frontend/src/components/ui/index.ts @@ -1,6 +1,6 @@ -export { default as Button } from './Button.svelte' -export { default as Card } from './Card.svelte' -export { default as Input } from './Input.svelte' -export { default as Message } from './Message.svelte' -export { default as Page } from './Page.svelte' -export { default as Section } from './Section.svelte' +export { default as Button } from "./Button.svelte"; +export { default as Card } from "./Card.svelte"; +export { default as Input } from "./Input.svelte"; +export { default as Message } from "./Message.svelte"; +export { default as Page } from "./Page.svelte"; +export { default as Section } from "./Section.svelte"; diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts index 3148d76..d24cd42 100644 --- a/frontend/src/lib/api.ts +++ b/frontend/src/lib/api.ts @@ -1,134 +1,160 @@ -const API_BASE = '/xrpc' +const API_BASE = "/xrpc"; export class ApiError extends Error { - public did?: string - public reauthMethods?: string[] - constructor(public status: number, public error: string, message: string, did?: string, reauthMethods?: string[]) { - super(message) - this.name = 'ApiError' - this.did = did - this.reauthMethods = reauthMethods + public did?: string; + public reauthMethods?: string[]; + constructor( + public status: number, + public error: string, + message: string, + did?: string, + reauthMethods?: string[], + ) { + super(message); + this.name = "ApiError"; + this.did = did; + this.reauthMethods = reauthMethods; } } -let tokenRefreshCallback: (() => Promise) | null = null +let tokenRefreshCallback: (() => Promise) | null = null; -export function setTokenRefreshCallback(callback: () => Promise) { - tokenRefreshCallback = callback +export function setTokenRefreshCallback( + callback: () => Promise, +) { + tokenRefreshCallback = callback; } async function xrpc(method: string, options?: { - method?: 'GET' | 'POST' - params?: Record - body?: unknown - token?: string - skipRetry?: boolean + method?: "GET" | "POST"; + params?: Record; + body?: unknown; + token?: string; + skipRetry?: boolean; }): Promise { - const { method: httpMethod = 'GET', params, body, token, skipRetry } = options ?? {} - let url = `${API_BASE}/${method}` + const { method: httpMethod = "GET", params, body, token, skipRetry } = + options ?? {}; + let url = `${API_BASE}/${method}`; if (params) { - const searchParams = new URLSearchParams(params) - url += `?${searchParams}` + const searchParams = new URLSearchParams(params); + url += `?${searchParams}`; } - const headers: Record = {} + const headers: Record = {}; if (token) { - headers['Authorization'] = `Bearer ${token}` + headers["Authorization"] = `Bearer ${token}`; } if (body) { - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json"; } const res = await fetch(url, { method: httpMethod, headers, body: body ? JSON.stringify(body) : undefined, - }) + }); if (!res.ok) { - const err = await res.json().catch(() => ({ error: 'Unknown', message: res.statusText })) - if (res.status === 401 && err.error === 'AuthenticationFailed' && token && tokenRefreshCallback && !skipRetry) { - const newToken = await tokenRefreshCallback() + const err = await res.json().catch(() => ({ + error: "Unknown", + message: res.statusText, + })); + if ( + res.status === 401 && err.error === "AuthenticationFailed" && token && + tokenRefreshCallback && !skipRetry + ) { + const newToken = await tokenRefreshCallback(); if (newToken && newToken !== token) { - return xrpc(method, { ...options, token: newToken, skipRetry: true }) + return xrpc(method, { ...options, token: newToken, skipRetry: true }); } } - throw new ApiError(res.status, err.error, err.message, err.did, err.reauthMethods) + throw new ApiError( + res.status, + err.error, + err.message, + err.did, + err.reauthMethods, + ); } - return res.json() + return res.json(); } export interface Session { - did: string - handle: string - email?: string - emailConfirmed?: boolean - preferredChannel?: string - preferredChannelVerified?: boolean - isAdmin?: boolean - active?: boolean - status?: 'active' | 'deactivated' - accessJwt: string - refreshJwt: string + did: string; + handle: string; + email?: string; + emailConfirmed?: boolean; + preferredChannel?: string; + preferredChannelVerified?: boolean; + isAdmin?: boolean; + active?: boolean; + status?: "active" | "deactivated"; + accessJwt: string; + refreshJwt: string; } export interface AppPassword { - name: string - createdAt: string + name: string; + createdAt: string; } export interface InviteCode { - code: string - available: number - disabled: boolean - forAccount: string - createdBy: string - createdAt: string - uses: { usedBy: string; usedAt: string }[] + code: string; + available: number; + disabled: boolean; + forAccount: string; + createdBy: string; + createdAt: string; + uses: { usedBy: string; usedAt: string }[]; } -export type VerificationChannel = 'email' | 'discord' | 'telegram' | 'signal' +export type VerificationChannel = "email" | "discord" | "telegram" | "signal"; -export type DidType = 'plc' | 'web' | 'web-external' +export type DidType = "plc" | "web" | "web-external"; export interface CreateAccountParams { - handle: string - email: string - password: string - inviteCode?: string - didType?: DidType - did?: string - signingKey?: string - verificationChannel?: VerificationChannel - discordId?: string - telegramUsername?: string - signalNumber?: string + handle: string; + email: string; + password: string; + inviteCode?: string; + didType?: DidType; + did?: string; + signingKey?: string; + verificationChannel?: VerificationChannel; + discordId?: string; + telegramUsername?: string; + signalNumber?: string; } export interface CreateAccountResult { - handle: string - did: string - verificationRequired: boolean - verificationChannel: string + handle: string; + did: string; + verificationRequired: boolean; + verificationChannel: string; } export interface ConfirmSignupResult { - accessJwt: string - refreshJwt: string - handle: string - did: string - email?: string - emailConfirmed?: boolean - preferredChannel?: string - preferredChannelVerified?: boolean + accessJwt: string; + refreshJwt: string; + handle: string; + did: string; + email?: string; + emailConfirmed?: boolean; + preferredChannel?: string; + preferredChannelVerified?: boolean; } export const api = { - async createAccount(params: CreateAccountParams, byodToken?: string): Promise { - const url = `${API_BASE}/com.atproto.server.createAccount` - const headers: Record = { 'Content-Type': 'application/json' } + async createAccount( + params: CreateAccountParams, + byodToken?: string, + ): Promise { + const url = `${API_BASE}/com.atproto.server.createAccount`; + const headers: Record = { + "Content-Type": "application/json", + }; if (byodToken) { - headers['Authorization'] = `Bearer ${byodToken}` + headers["Authorization"] = `Bearer ${byodToken}`; } const response = await fetch(url, { - method: 'POST', + method: "POST", headers, body: JSON.stringify({ handle: params.handle, @@ -143,742 +169,888 @@ export const api = { telegramUsername: params.telegramUsername, signalNumber: params.signalNumber, }), - }) - const data = await response.json() + }); + const data = await response.json(); if (!response.ok) { - throw new ApiError(data.error, data.message, response.status) + throw new ApiError(data.error, data.message, response.status); } - return data + return data; }, - async confirmSignup(did: string, verificationCode: string): Promise { - return xrpc('com.atproto.server.confirmSignup', { - method: 'POST', + async confirmSignup( + did: string, + verificationCode: string, + ): Promise { + return xrpc("com.atproto.server.confirmSignup", { + method: "POST", body: { did, verificationCode }, - }) + }); }, async resendVerification(did: string): Promise<{ success: boolean }> { - return xrpc('com.atproto.server.resendVerification', { - method: 'POST', + return xrpc("com.atproto.server.resendVerification", { + method: "POST", body: { did }, - }) + }); }, async createSession(identifier: string, password: string): Promise { - return xrpc('com.atproto.server.createSession', { - method: 'POST', + return xrpc("com.atproto.server.createSession", { + method: "POST", body: { identifier, password }, - }) + }); }, async getSession(token: string): Promise { - return xrpc('com.atproto.server.getSession', { token }) + return xrpc("com.atproto.server.getSession", { token }); }, async refreshSession(refreshJwt: string): Promise { - return xrpc('com.atproto.server.refreshSession', { - method: 'POST', + return xrpc("com.atproto.server.refreshSession", { + method: "POST", token: refreshJwt, - }) + }); }, async deleteSession(token: string): Promise { - await xrpc('com.atproto.server.deleteSession', { - method: 'POST', + await xrpc("com.atproto.server.deleteSession", { + method: "POST", token, - }) + }); }, async listAppPasswords(token: string): Promise<{ passwords: AppPassword[] }> { - return xrpc('com.atproto.server.listAppPasswords', { token }) + return xrpc("com.atproto.server.listAppPasswords", { token }); }, - async createAppPassword(token: string, name: string): Promise<{ name: string; password: string; createdAt: string }> { - return xrpc('com.atproto.server.createAppPassword', { - method: 'POST', + async createAppPassword( + token: string, + name: string, + ): Promise<{ name: string; password: string; createdAt: string }> { + return xrpc("com.atproto.server.createAppPassword", { + method: "POST", token, body: { name }, - }) + }); }, async revokeAppPassword(token: string, name: string): Promise { - await xrpc('com.atproto.server.revokeAppPassword', { - method: 'POST', + await xrpc("com.atproto.server.revokeAppPassword", { + method: "POST", token, body: { name }, - }) + }); }, async getAccountInviteCodes(token: string): Promise<{ codes: InviteCode[] }> { - return xrpc('com.atproto.server.getAccountInviteCodes', { token }) + return xrpc("com.atproto.server.getAccountInviteCodes", { token }); }, - async createInviteCode(token: string, useCount: number = 1): Promise<{ code: string }> { - return xrpc('com.atproto.server.createInviteCode', { - method: 'POST', + async createInviteCode( + token: string, + useCount: number = 1, + ): Promise<{ code: string }> { + return xrpc("com.atproto.server.createInviteCode", { + method: "POST", token, body: { useCount }, - }) + }); }, async requestPasswordReset(email: string): Promise { - await xrpc('com.atproto.server.requestPasswordReset', { - method: 'POST', + await xrpc("com.atproto.server.requestPasswordReset", { + method: "POST", body: { email }, - }) + }); }, async resetPassword(token: string, password: string): Promise { - await xrpc('com.atproto.server.resetPassword', { - method: 'POST', + await xrpc("com.atproto.server.resetPassword", { + method: "POST", body: { token, password }, - }) + }); }, - async requestEmailUpdate(token: string, email: string): Promise<{ tokenRequired: boolean }> { - return xrpc('com.atproto.server.requestEmailUpdate', { - method: 'POST', + async requestEmailUpdate( + token: string, + email: string, + ): Promise<{ tokenRequired: boolean }> { + return xrpc("com.atproto.server.requestEmailUpdate", { + method: "POST", token, body: { email }, - }) + }); }, - async updateEmail(token: string, email: string, emailToken?: string): Promise { - await xrpc('com.atproto.server.updateEmail', { - method: 'POST', + async updateEmail( + token: string, + email: string, + emailToken?: string, + ): Promise { + await xrpc("com.atproto.server.updateEmail", { + method: "POST", token, body: { email, token: emailToken }, - }) + }); }, async updateHandle(token: string, handle: string): Promise { - await xrpc('com.atproto.identity.updateHandle', { - method: 'POST', + await xrpc("com.atproto.identity.updateHandle", { + method: "POST", token, body: { handle }, - }) + }); }, async requestAccountDelete(token: string): Promise { - await xrpc('com.atproto.server.requestAccountDelete', { - method: 'POST', + await xrpc("com.atproto.server.requestAccountDelete", { + method: "POST", token, - }) + }); }, - async deleteAccount(did: string, password: string, deleteToken: string): Promise { - await xrpc('com.atproto.server.deleteAccount', { - method: 'POST', + async deleteAccount( + did: string, + password: string, + deleteToken: string, + ): Promise { + await xrpc("com.atproto.server.deleteAccount", { + method: "POST", body: { did, password, token: deleteToken }, - }) + }); }, async describeServer(): Promise<{ - availableUserDomains: string[] - inviteCodeRequired: boolean - links?: { privacyPolicy?: string; termsOfService?: string } - version?: string - availableCommsChannels?: string[] + availableUserDomains: string[]; + inviteCodeRequired: boolean; + links?: { privacyPolicy?: string; termsOfService?: string }; + version?: string; + availableCommsChannels?: string[]; }> { - return xrpc('com.atproto.server.describeServer') + return xrpc("com.atproto.server.describeServer"); }, async listRepos(limit?: number): Promise<{ - repos: Array<{ did: string; head: string; rev: string }> - cursor?: string + repos: Array<{ did: string; head: string; rev: string }>; + cursor?: string; }> { - const params: Record = {} - if (limit) params.limit = String(limit) - return xrpc('com.atproto.sync.listRepos', { params }) + const params: Record = {}; + if (limit) params.limit = String(limit); + return xrpc("com.atproto.sync.listRepos", { params }); }, async getNotificationPrefs(token: string): Promise<{ - preferredChannel: string - email: string - discordId: string | null - discordVerified: boolean - telegramUsername: string | null - telegramVerified: boolean - signalNumber: string | null - signalVerified: boolean + preferredChannel: string; + email: string; + discordId: string | null; + discordVerified: boolean; + telegramUsername: string | null; + telegramVerified: boolean; + signalNumber: string | null; + signalVerified: boolean; }> { - return xrpc('com.tranquil.account.getNotificationPrefs', { token }) + return xrpc("com.tranquil.account.getNotificationPrefs", { token }); }, async updateNotificationPrefs(token: string, prefs: { - preferredChannel?: string - discordId?: string - telegramUsername?: string - signalNumber?: string + preferredChannel?: string; + discordId?: string; + telegramUsername?: string; + signalNumber?: string; }): Promise<{ success: boolean }> { - return xrpc('com.tranquil.account.updateNotificationPrefs', { - method: 'POST', + return xrpc("com.tranquil.account.updateNotificationPrefs", { + method: "POST", token, body: prefs, - }) + }); }, - async confirmChannelVerification(token: string, channel: string, identifier: string, code: string): Promise<{ success: boolean }> { - return xrpc('com.tranquil.account.confirmChannelVerification', { - method: 'POST', + async confirmChannelVerification( + token: string, + channel: string, + identifier: string, + code: string, + ): Promise<{ success: boolean }> { + return xrpc("com.tranquil.account.confirmChannelVerification", { + method: "POST", token, body: { channel, identifier, code }, - }) + }); }, async getNotificationHistory(token: string): Promise<{ notifications: Array<{ - createdAt: string - channel: string - notificationType: string - status: string - subject: string | null - body: string - }> + createdAt: string; + channel: string; + notificationType: string; + status: string; + subject: string | null; + body: string; + }>; }> { - return xrpc('com.tranquil.account.getNotificationHistory', { token }) + return xrpc("com.tranquil.account.getNotificationHistory", { token }); }, async getServerStats(token: string): Promise<{ - userCount: number - repoCount: number - recordCount: number - blobStorageBytes: number + userCount: number; + repoCount: number; + recordCount: number; + blobStorageBytes: number; }> { - return xrpc('com.tranquil.admin.getServerStats', { token }) + return xrpc("com.tranquil.admin.getServerStats", { token }); }, async getServerConfig(): Promise<{ - serverName: string - primaryColor: string | null - primaryColorDark: string | null - secondaryColor: string | null - secondaryColorDark: string | null - logoCid: string | null + serverName: string; + primaryColor: string | null; + primaryColorDark: string | null; + secondaryColor: string | null; + secondaryColorDark: string | null; + logoCid: string | null; }> { - return xrpc('com.tranquil.server.getConfig') + return xrpc("com.tranquil.server.getConfig"); }, async updateServerConfig( token: string, config: { - serverName?: string - primaryColor?: string - primaryColorDark?: string - secondaryColor?: string - secondaryColorDark?: string - logoCid?: string - } + serverName?: string; + primaryColor?: string; + primaryColorDark?: string; + secondaryColor?: string; + secondaryColorDark?: string; + logoCid?: string; + }, ): Promise<{ success: boolean }> { - return xrpc('com.tranquil.admin.updateServerConfig', { - method: 'POST', + return xrpc("com.tranquil.admin.updateServerConfig", { + method: "POST", token, body: config, - }) + }); }, - async uploadBlob(token: string, file: File): Promise<{ blob: { $type: string; ref: { $link: string }; mimeType: string; size: number } }> { - const res = await fetch('/xrpc/com.atproto.repo.uploadBlob', { - method: 'POST', + async uploadBlob( + token: string, + file: File, + ): Promise< + { + blob: { + $type: string; + ref: { $link: string }; + mimeType: string; + size: number; + }; + } + > { + const res = await fetch("/xrpc/com.atproto.repo.uploadBlob", { + method: "POST", headers: { - 'Authorization': `Bearer ${token}`, - 'Content-Type': file.type, + "Authorization": `Bearer ${token}`, + "Content-Type": file.type, }, body: file, - }) + }); if (!res.ok) { - const err = await res.json().catch(() => ({ error: 'Unknown', message: res.statusText })) - throw new ApiError(res.status, err.error, err.message) + const err = await res.json().catch(() => ({ + error: "Unknown", + message: res.statusText, + })); + throw new ApiError(res.status, err.error, err.message); } - return res.json() + return res.json(); }, - async changePassword(token: string, currentPassword: string, newPassword: string): Promise { - await xrpc('com.tranquil.account.changePassword', { - method: 'POST', + async changePassword( + token: string, + currentPassword: string, + newPassword: string, + ): Promise { + await xrpc("com.tranquil.account.changePassword", { + method: "POST", token, body: { currentPassword, newPassword }, - }) + }); }, async removePassword(token: string): Promise<{ success: boolean }> { - return xrpc('com.tranquil.account.removePassword', { - method: 'POST', + return xrpc("com.tranquil.account.removePassword", { + method: "POST", token, - }) + }); }, async getPasswordStatus(token: string): Promise<{ hasPassword: boolean }> { - return xrpc('com.tranquil.account.getPasswordStatus', { token }) + return xrpc("com.tranquil.account.getPasswordStatus", { token }); }, - async getLegacyLoginPreference(token: string): Promise<{ allowLegacyLogin: boolean; hasMfa: boolean }> { - return xrpc('com.tranquil.account.getLegacyLoginPreference', { token }) + async getLegacyLoginPreference( + token: string, + ): Promise<{ allowLegacyLogin: boolean; hasMfa: boolean }> { + return xrpc("com.tranquil.account.getLegacyLoginPreference", { token }); }, - async updateLegacyLoginPreference(token: string, allowLegacyLogin: boolean): Promise<{ allowLegacyLogin: boolean }> { - return xrpc('com.tranquil.account.updateLegacyLoginPreference', { - method: 'POST', + async updateLegacyLoginPreference( + token: string, + allowLegacyLogin: boolean, + ): Promise<{ allowLegacyLogin: boolean }> { + return xrpc("com.tranquil.account.updateLegacyLoginPreference", { + method: "POST", token, body: { allowLegacyLogin }, - }) + }); }, - async updateLocale(token: string, preferredLocale: string): Promise<{ preferredLocale: string }> { - return xrpc('com.tranquil.account.updateLocale', { - method: 'POST', + async updateLocale( + token: string, + preferredLocale: string, + ): Promise<{ preferredLocale: string }> { + return xrpc("com.tranquil.account.updateLocale", { + method: "POST", token, body: { preferredLocale }, - }) + }); }, async listSessions(token: string): Promise<{ sessions: Array<{ - id: string - sessionType: string - clientName: string | null - createdAt: string - expiresAt: string - isCurrent: boolean - }> + id: string; + sessionType: string; + clientName: string | null; + createdAt: string; + expiresAt: string; + isCurrent: boolean; + }>; }> { - return xrpc('com.tranquil.account.listSessions', { token }) + return xrpc("com.tranquil.account.listSessions", { token }); }, async revokeSession(token: string, sessionId: string): Promise { - await xrpc('com.tranquil.account.revokeSession', { - method: 'POST', + await xrpc("com.tranquil.account.revokeSession", { + method: "POST", token, body: { sessionId }, - }) + }); }, async revokeAllSessions(token: string): Promise<{ revokedCount: number }> { - return xrpc('com.tranquil.account.revokeAllSessions', { - method: 'POST', + return xrpc("com.tranquil.account.revokeAllSessions", { + method: "POST", token, - }) + }); }, async searchAccounts(token: string, options?: { - handle?: string - cursor?: string - limit?: number + handle?: string; + cursor?: string; + limit?: number; }): Promise<{ - cursor?: string + cursor?: string; accounts: Array<{ - did: string - handle: string - email?: string - indexedAt: string - emailConfirmedAt?: string - deactivatedAt?: string - }> + did: string; + handle: string; + email?: string; + indexedAt: string; + emailConfirmedAt?: string; + deactivatedAt?: string; + }>; }> { - const params: Record = {} - if (options?.handle) params.handle = options.handle - if (options?.cursor) params.cursor = options.cursor - if (options?.limit) params.limit = String(options.limit) - return xrpc('com.atproto.admin.searchAccounts', { token, params }) + const params: Record = {}; + if (options?.handle) params.handle = options.handle; + if (options?.cursor) params.cursor = options.cursor; + if (options?.limit) params.limit = String(options.limit); + return xrpc("com.atproto.admin.searchAccounts", { token, params }); }, async getInviteCodes(token: string, options?: { - sort?: 'recent' | 'usage' - cursor?: string - limit?: number + sort?: "recent" | "usage"; + cursor?: string; + limit?: number; }): Promise<{ - cursor?: string + cursor?: string; codes: Array<{ - code: string - available: number - disabled: boolean - forAccount: string - createdBy: string - createdAt: string - uses: Array<{ usedBy: string; usedAt: string }> - }> + code: string; + available: number; + disabled: boolean; + forAccount: string; + createdBy: string; + createdAt: string; + uses: Array<{ usedBy: string; usedAt: string }>; + }>; }> { - const params: Record = {} - if (options?.sort) params.sort = options.sort - if (options?.cursor) params.cursor = options.cursor - if (options?.limit) params.limit = String(options.limit) - return xrpc('com.atproto.admin.getInviteCodes', { token, params }) + const params: Record = {}; + if (options?.sort) params.sort = options.sort; + if (options?.cursor) params.cursor = options.cursor; + if (options?.limit) params.limit = String(options.limit); + return xrpc("com.atproto.admin.getInviteCodes", { token, params }); }, - async disableInviteCodes(token: string, codes?: string[], accounts?: string[]): Promise { - await xrpc('com.atproto.admin.disableInviteCodes', { - method: 'POST', + async disableInviteCodes( + token: string, + codes?: string[], + accounts?: string[], + ): Promise { + await xrpc("com.atproto.admin.disableInviteCodes", { + method: "POST", token, body: { codes, accounts }, - }) + }); }, async getAccountInfo(token: string, did: string): Promise<{ - did: string - handle: string - email?: string - indexedAt: string - emailConfirmedAt?: string - invitesDisabled?: boolean - deactivatedAt?: string + did: string; + handle: string; + email?: string; + indexedAt: string; + emailConfirmedAt?: string; + invitesDisabled?: boolean; + deactivatedAt?: string; }> { - return xrpc('com.atproto.admin.getAccountInfo', { token, params: { did } }) + return xrpc("com.atproto.admin.getAccountInfo", { token, params: { did } }); }, async disableAccountInvites(token: string, account: string): Promise { - await xrpc('com.atproto.admin.disableAccountInvites', { - method: 'POST', + await xrpc("com.atproto.admin.disableAccountInvites", { + method: "POST", token, body: { account }, - }) + }); }, async enableAccountInvites(token: string, account: string): Promise { - await xrpc('com.atproto.admin.enableAccountInvites', { - method: 'POST', + await xrpc("com.atproto.admin.enableAccountInvites", { + method: "POST", token, body: { account }, - }) + }); }, async adminDeleteAccount(token: string, did: string): Promise { - await xrpc('com.atproto.admin.deleteAccount', { - method: 'POST', + await xrpc("com.atproto.admin.deleteAccount", { + method: "POST", token, body: { did }, - }) + }); }, async describeRepo(token: string, repo: string): Promise<{ - handle: string - did: string - didDoc: unknown - collections: string[] - handleIsCorrect: boolean + handle: string; + did: string; + didDoc: unknown; + collections: string[]; + handleIsCorrect: boolean; }> { - return xrpc('com.atproto.repo.describeRepo', { + return xrpc("com.atproto.repo.describeRepo", { token, params: { repo }, - }) + }); }, async listRecords(token: string, repo: string, collection: string, options?: { - limit?: number - cursor?: string - reverse?: boolean + limit?: number; + cursor?: string; + reverse?: boolean; }): Promise<{ - records: Array<{ uri: string; cid: string; value: unknown }> - cursor?: string + records: Array<{ uri: string; cid: string; value: unknown }>; + cursor?: string; }> { - const params: Record = { repo, collection } - if (options?.limit) params.limit = String(options.limit) - if (options?.cursor) params.cursor = options.cursor - if (options?.reverse) params.reverse = 'true' - return xrpc('com.atproto.repo.listRecords', { token, params }) + const params: Record = { repo, collection }; + if (options?.limit) params.limit = String(options.limit); + if (options?.cursor) params.cursor = options.cursor; + if (options?.reverse) params.reverse = "true"; + return xrpc("com.atproto.repo.listRecords", { token, params }); }, - async getRecord(token: string, repo: string, collection: string, rkey: string): Promise<{ - uri: string - cid: string - value: unknown + async getRecord( + token: string, + repo: string, + collection: string, + rkey: string, + ): Promise<{ + uri: string; + cid: string; + value: unknown; }> { - return xrpc('com.atproto.repo.getRecord', { + return xrpc("com.atproto.repo.getRecord", { token, params: { repo, collection, rkey }, - }) + }); }, - async createRecord(token: string, repo: string, collection: string, record: unknown, rkey?: string): Promise<{ - uri: string - cid: string + async createRecord( + token: string, + repo: string, + collection: string, + record: unknown, + rkey?: string, + ): Promise<{ + uri: string; + cid: string; }> { - return xrpc('com.atproto.repo.createRecord', { - method: 'POST', + return xrpc("com.atproto.repo.createRecord", { + method: "POST", token, body: { repo, collection, record, rkey }, - }) + }); }, - async putRecord(token: string, repo: string, collection: string, rkey: string, record: unknown): Promise<{ - uri: string - cid: string + async putRecord( + token: string, + repo: string, + collection: string, + rkey: string, + record: unknown, + ): Promise<{ + uri: string; + cid: string; }> { - return xrpc('com.atproto.repo.putRecord', { - method: 'POST', + return xrpc("com.atproto.repo.putRecord", { + method: "POST", token, body: { repo, collection, rkey, record }, - }) + }); }, - async deleteRecord(token: string, repo: string, collection: string, rkey: string): Promise { - await xrpc('com.atproto.repo.deleteRecord', { - method: 'POST', + async deleteRecord( + token: string, + repo: string, + collection: string, + rkey: string, + ): Promise { + await xrpc("com.atproto.repo.deleteRecord", { + method: "POST", token, body: { repo, collection, rkey }, - }) + }); }, - async getTotpStatus(token: string): Promise<{ enabled: boolean; hasBackupCodes: boolean }> { - return xrpc('com.atproto.server.getTotpStatus', { token }) + async getTotpStatus( + token: string, + ): Promise<{ enabled: boolean; hasBackupCodes: boolean }> { + return xrpc("com.atproto.server.getTotpStatus", { token }); }, - async createTotpSecret(token: string): Promise<{ uri: string; qrBase64: string }> { - return xrpc('com.atproto.server.createTotpSecret', { method: 'POST', token }) + async createTotpSecret( + token: string, + ): Promise<{ uri: string; qrBase64: string }> { + return xrpc("com.atproto.server.createTotpSecret", { + method: "POST", + token, + }); }, - async enableTotp(token: string, code: string): Promise<{ success: boolean; backupCodes: string[] }> { - return xrpc('com.atproto.server.enableTotp', { - method: 'POST', + async enableTotp( + token: string, + code: string, + ): Promise<{ success: boolean; backupCodes: string[] }> { + return xrpc("com.atproto.server.enableTotp", { + method: "POST", token, body: { code }, - }) + }); }, - async disableTotp(token: string, password: string, code: string): Promise<{ success: boolean }> { - return xrpc('com.atproto.server.disableTotp', { - method: 'POST', + async disableTotp( + token: string, + password: string, + code: string, + ): Promise<{ success: boolean }> { + return xrpc("com.atproto.server.disableTotp", { + method: "POST", token, body: { password, code }, - }) + }); }, - async regenerateBackupCodes(token: string, password: string, code: string): Promise<{ backupCodes: string[] }> { - return xrpc('com.atproto.server.regenerateBackupCodes', { - method: 'POST', + async regenerateBackupCodes( + token: string, + password: string, + code: string, + ): Promise<{ backupCodes: string[] }> { + return xrpc("com.atproto.server.regenerateBackupCodes", { + method: "POST", token, body: { password, code }, - }) + }); }, - async startPasskeyRegistration(token: string, friendlyName?: string): Promise<{ options: unknown }> { - return xrpc('com.atproto.server.startPasskeyRegistration', { - method: 'POST', + async startPasskeyRegistration( + token: string, + friendlyName?: string, + ): Promise<{ options: unknown }> { + return xrpc("com.atproto.server.startPasskeyRegistration", { + method: "POST", token, body: { friendlyName }, - }) + }); }, - async finishPasskeyRegistration(token: string, credential: unknown, friendlyName?: string): Promise<{ id: string; credentialId: string }> { - return xrpc('com.atproto.server.finishPasskeyRegistration', { - method: 'POST', + async finishPasskeyRegistration( + token: string, + credential: unknown, + friendlyName?: string, + ): Promise<{ id: string; credentialId: string }> { + return xrpc("com.atproto.server.finishPasskeyRegistration", { + method: "POST", token, body: { credential, friendlyName }, - }) + }); }, async listPasskeys(token: string): Promise<{ passkeys: Array<{ - id: string - credentialId: string - friendlyName: string | null - createdAt: string - lastUsed: string | null - }> + id: string; + credentialId: string; + friendlyName: string | null; + createdAt: string; + lastUsed: string | null; + }>; }> { - return xrpc('com.atproto.server.listPasskeys', { token }) + return xrpc("com.atproto.server.listPasskeys", { token }); }, async deletePasskey(token: string, id: string): Promise { - await xrpc('com.atproto.server.deletePasskey', { - method: 'POST', + await xrpc("com.atproto.server.deletePasskey", { + method: "POST", token, body: { id }, - }) + }); }, - async updatePasskey(token: string, id: string, friendlyName: string): Promise { - await xrpc('com.atproto.server.updatePasskey', { - method: 'POST', + async updatePasskey( + token: string, + id: string, + friendlyName: string, + ): Promise { + await xrpc("com.atproto.server.updatePasskey", { + method: "POST", token, body: { id, friendlyName }, - }) + }); }, async listTrustedDevices(token: string): Promise<{ devices: Array<{ - id: string - userAgent: string | null - friendlyName: string | null - trustedAt: string | null - trustedUntil: string | null - lastSeenAt: string - }> + id: string; + userAgent: string | null; + friendlyName: string | null; + trustedAt: string | null; + trustedUntil: string | null; + lastSeenAt: string; + }>; }> { - return xrpc('com.tranquil.account.listTrustedDevices', { token }) + return xrpc("com.tranquil.account.listTrustedDevices", { token }); }, - async revokeTrustedDevice(token: string, deviceId: string): Promise<{ success: boolean }> { - return xrpc('com.tranquil.account.revokeTrustedDevice', { - method: 'POST', + async revokeTrustedDevice( + token: string, + deviceId: string, + ): Promise<{ success: boolean }> { + return xrpc("com.tranquil.account.revokeTrustedDevice", { + method: "POST", token, body: { deviceId }, - }) + }); }, - async updateTrustedDevice(token: string, deviceId: string, friendlyName: string): Promise<{ success: boolean }> { - return xrpc('com.tranquil.account.updateTrustedDevice', { - method: 'POST', + async updateTrustedDevice( + token: string, + deviceId: string, + friendlyName: string, + ): Promise<{ success: boolean }> { + return xrpc("com.tranquil.account.updateTrustedDevice", { + method: "POST", token, body: { deviceId, friendlyName }, - }) + }); }, async getReauthStatus(token: string): Promise<{ - requiresReauth: boolean - lastReauthAt: string | null - availableMethods: string[] + requiresReauth: boolean; + lastReauthAt: string | null; + availableMethods: string[]; }> { - return xrpc('com.tranquil.account.getReauthStatus', { token }) + return xrpc("com.tranquil.account.getReauthStatus", { token }); }, - async reauthPassword(token: string, password: string): Promise<{ success: boolean; reauthAt: string }> { - return xrpc('com.tranquil.account.reauthPassword', { - method: 'POST', + async reauthPassword( + token: string, + password: string, + ): Promise<{ success: boolean; reauthAt: string }> { + return xrpc("com.tranquil.account.reauthPassword", { + method: "POST", token, body: { password }, - }) + }); }, - async reauthTotp(token: string, code: string): Promise<{ success: boolean; reauthAt: string }> { - return xrpc('com.tranquil.account.reauthTotp', { - method: 'POST', + async reauthTotp( + token: string, + code: string, + ): Promise<{ success: boolean; reauthAt: string }> { + return xrpc("com.tranquil.account.reauthTotp", { + method: "POST", token, body: { code }, - }) + }); }, async reauthPasskeyStart(token: string): Promise<{ options: unknown }> { - return xrpc('com.tranquil.account.reauthPasskeyStart', { - method: 'POST', + return xrpc("com.tranquil.account.reauthPasskeyStart", { + method: "POST", token, - }) + }); }, - async reauthPasskeyFinish(token: string, credential: unknown): Promise<{ success: boolean; reauthAt: string }> { - return xrpc('com.tranquil.account.reauthPasskeyFinish', { - method: 'POST', + async reauthPasskeyFinish( + token: string, + credential: unknown, + ): Promise<{ success: boolean; reauthAt: string }> { + return xrpc("com.tranquil.account.reauthPasskeyFinish", { + method: "POST", token, body: { credential }, - }) + }); }, async reserveSigningKey(did?: string): Promise<{ signingKey: string }> { - return xrpc('com.atproto.server.reserveSigningKey', { - method: 'POST', + return xrpc("com.atproto.server.reserveSigningKey", { + method: "POST", body: { did }, - }) + }); }, async getRecommendedDidCredentials(token: string): Promise<{ - rotationKeys?: string[] - alsoKnownAs?: string[] - verificationMethods?: { atproto?: string } - services?: { atproto_pds?: { type: string; endpoint: string } } + rotationKeys?: string[]; + alsoKnownAs?: string[]; + verificationMethods?: { atproto?: string }; + services?: { atproto_pds?: { type: string; endpoint: string } }; }> { - return xrpc('com.atproto.identity.getRecommendedDidCredentials', { token }) + return xrpc("com.atproto.identity.getRecommendedDidCredentials", { token }); }, async activateAccount(token: string): Promise { - await xrpc('com.atproto.server.activateAccount', { - method: 'POST', + await xrpc("com.atproto.server.activateAccount", { + method: "POST", token, - }) + }); }, async createPasskeyAccount(params: { - handle: string - email?: string - inviteCode?: string - didType?: DidType - did?: string - signingKey?: string - verificationChannel?: VerificationChannel - discordId?: string - telegramUsername?: string - signalNumber?: string + handle: string; + email?: string; + inviteCode?: string; + didType?: DidType; + did?: string; + signingKey?: string; + verificationChannel?: VerificationChannel; + discordId?: string; + telegramUsername?: string; + signalNumber?: string; }, byodToken?: string): Promise<{ - did: string - handle: string - setupToken: string - setupExpiresAt: string + did: string; + handle: string; + setupToken: string; + setupExpiresAt: string; }> { - const url = `${API_BASE}/com.tranquil.account.createPasskeyAccount` + const url = `${API_BASE}/com.tranquil.account.createPasskeyAccount`; const headers: Record = { - 'Content-Type': 'application/json' - } + "Content-Type": "application/json", + }; if (byodToken) { - headers['Authorization'] = `Bearer ${byodToken}` + headers["Authorization"] = `Bearer ${byodToken}`; } const res = await fetch(url, { - method: 'POST', + method: "POST", headers, body: JSON.stringify(params), - }) + }); if (!res.ok) { - const err = await res.json().catch(() => ({ error: 'Unknown', message: res.statusText })) - throw new ApiError(res.status, err.error, err.message) + const err = await res.json().catch(() => ({ + error: "Unknown", + message: res.statusText, + })); + throw new ApiError(res.status, err.error, err.message); } - return res.json() + return res.json(); }, - async startPasskeyRegistrationForSetup(did: string, setupToken: string, friendlyName?: string): Promise<{ options: unknown }> { - return xrpc('com.tranquil.account.startPasskeyRegistrationForSetup', { - method: 'POST', + async startPasskeyRegistrationForSetup( + did: string, + setupToken: string, + friendlyName?: string, + ): Promise<{ options: unknown }> { + return xrpc("com.tranquil.account.startPasskeyRegistrationForSetup", { + method: "POST", body: { did, setupToken, friendlyName }, - }) + }); }, - async completePasskeySetup(did: string, setupToken: string, passkeyCredential: unknown, passkeyFriendlyName?: string): Promise<{ - did: string - handle: string - appPassword: string - appPasswordName: string + async completePasskeySetup( + did: string, + setupToken: string, + passkeyCredential: unknown, + passkeyFriendlyName?: string, + ): Promise<{ + did: string; + handle: string; + appPassword: string; + appPasswordName: string; }> { - return xrpc('com.tranquil.account.completePasskeySetup', { - method: 'POST', + return xrpc("com.tranquil.account.completePasskeySetup", { + method: "POST", body: { did, setupToken, passkeyCredential, passkeyFriendlyName }, - }) + }); }, async requestPasskeyRecovery(email: string): Promise<{ success: boolean }> { - return xrpc('com.tranquil.account.requestPasskeyRecovery', { - method: 'POST', + return xrpc("com.tranquil.account.requestPasskeyRecovery", { + method: "POST", body: { email }, - }) + }); }, - async recoverPasskeyAccount(did: string, recoveryToken: string, newPassword: string): Promise<{ success: boolean }> { - return xrpc('com.tranquil.account.recoverPasskeyAccount', { - method: 'POST', + async recoverPasskeyAccount( + did: string, + recoveryToken: string, + newPassword: string, + ): Promise<{ success: boolean }> { + return xrpc("com.tranquil.account.recoverPasskeyAccount", { + method: "POST", body: { did, recoveryToken, newPassword }, - }) + }); }, - async verifyMigrationEmail(token: string, email: string): Promise<{ success: boolean; did: string }> { - return xrpc('com.atproto.server.verifyMigrationEmail', { - method: 'POST', + async verifyMigrationEmail( + token: string, + email: string, + ): Promise<{ success: boolean; did: string }> { + return xrpc("com.atproto.server.verifyMigrationEmail", { + method: "POST", body: { token, email }, - }) + }); }, async resendMigrationVerification(email: string): Promise<{ sent: boolean }> { - return xrpc('com.atproto.server.resendMigrationVerification', { - method: 'POST', + return xrpc("com.atproto.server.resendMigrationVerification", { + method: "POST", body: { email }, - }) + }); }, - async verifyToken(token: string, identifier: string, accessToken?: string): Promise<{ - success: boolean - did: string - purpose: string - channel: string + async verifyToken( + token: string, + identifier: string, + accessToken?: string, + ): Promise<{ + success: boolean; + did: string; + purpose: string; + channel: string; }> { - return xrpc('com.tranquil.account.verifyToken', { - method: 'POST', + return xrpc("com.tranquil.account.verifyToken", { + method: "POST", body: { token, identifier }, token: accessToken, - }) + }); }, -} +}; diff --git a/frontend/src/lib/auth.svelte.ts b/frontend/src/lib/auth.svelte.ts index f854608..b5e5fd5 100644 --- a/frontend/src/lib/auth.svelte.ts +++ b/frontend/src/lib/auth.svelte.ts @@ -1,28 +1,43 @@ -import { api, setTokenRefreshCallback, type Session, type CreateAccountParams, type CreateAccountResult, ApiError } from './api' -import { startOAuthLogin, handleOAuthCallback, checkForOAuthCallback, clearOAuthCallbackParams, refreshOAuthToken } from './oauth' -import { setLocale, type SupportedLocale } from './i18n' +import { + api, + ApiError, + type CreateAccountParams, + type CreateAccountResult, + type Session, + setTokenRefreshCallback, +} from "./api"; +import { + checkForOAuthCallback, + clearOAuthCallbackParams, + handleOAuthCallback, + refreshOAuthToken, + startOAuthLogin, +} from "./oauth"; +import { setLocale, type SupportedLocale } from "./i18n"; -function applyLocaleFromSession(sessionInfo: { preferredLocale?: string | null }) { +function applyLocaleFromSession( + sessionInfo: { preferredLocale?: string | null }, +) { if (sessionInfo.preferredLocale) { - setLocale(sessionInfo.preferredLocale as SupportedLocale) + setLocale(sessionInfo.preferredLocale as SupportedLocale); } } -const STORAGE_KEY = 'tranquil_pds_session' -const ACCOUNTS_KEY = 'tranquil_pds_accounts' +const STORAGE_KEY = "tranquil_pds_session"; +const ACCOUNTS_KEY = "tranquil_pds_accounts"; export interface SavedAccount { - did: string - handle: string - accessJwt: string - refreshJwt: string + did: string; + handle: string; + accessJwt: string; + refreshJwt: string; } interface AuthState { - session: Session | null - loading: boolean - error: string | null - savedAccounts: SavedAccount[] + session: Session | null; + loading: boolean; + error: string | null; + savedAccounts: SavedAccount[]; } let state = $state({ @@ -30,205 +45,222 @@ let state = $state({ loading: true, error: null, savedAccounts: [], -}) +}); function saveSession(session: Session | null) { if (session) { - localStorage.setItem(STORAGE_KEY, JSON.stringify(session)) + localStorage.setItem(STORAGE_KEY, JSON.stringify(session)); } else { - localStorage.removeItem(STORAGE_KEY) + localStorage.removeItem(STORAGE_KEY); } } function loadSession(): Session | null { - const stored = localStorage.getItem(STORAGE_KEY) + const stored = localStorage.getItem(STORAGE_KEY); if (stored) { try { - return JSON.parse(stored) + return JSON.parse(stored); } catch { - return null + return null; } } - return null + return null; } function loadSavedAccounts(): SavedAccount[] { - const stored = localStorage.getItem(ACCOUNTS_KEY) + const stored = localStorage.getItem(ACCOUNTS_KEY); if (stored) { try { - return JSON.parse(stored) + return JSON.parse(stored); } catch { - return [] + return []; } } - return [] + return []; } function saveSavedAccounts(accounts: SavedAccount[]) { - localStorage.setItem(ACCOUNTS_KEY, JSON.stringify(accounts)) + localStorage.setItem(ACCOUNTS_KEY, JSON.stringify(accounts)); } function addOrUpdateSavedAccount(session: Session) { - const accounts = loadSavedAccounts() - const existing = accounts.findIndex(a => a.did === session.did) + const accounts = loadSavedAccounts(); + const existing = accounts.findIndex((a) => a.did === session.did); const savedAccount: SavedAccount = { did: session.did, handle: session.handle, accessJwt: session.accessJwt, refreshJwt: session.refreshJwt, - } + }; if (existing >= 0) { - accounts[existing] = savedAccount + accounts[existing] = savedAccount; } else { - accounts.push(savedAccount) + accounts.push(savedAccount); } - saveSavedAccounts(accounts) - state.savedAccounts = accounts + saveSavedAccounts(accounts); + state.savedAccounts = accounts; } function removeSavedAccount(did: string) { - const accounts = loadSavedAccounts().filter(a => a.did !== did) - saveSavedAccounts(accounts) - state.savedAccounts = accounts + const accounts = loadSavedAccounts().filter((a) => a.did !== did); + saveSavedAccounts(accounts); + state.savedAccounts = accounts; } async function tryRefreshToken(): Promise { - if (!state.session) return null + if (!state.session) return null; try { - const tokens = await refreshOAuthToken(state.session.refreshJwt) - const sessionInfo = await api.getSession(tokens.access_token) + const tokens = await refreshOAuthToken(state.session.refreshJwt); + const sessionInfo = await api.getSession(tokens.access_token); const session: Session = { ...sessionInfo, accessJwt: tokens.access_token, refreshJwt: tokens.refresh_token || state.session.refreshJwt, - } - state.session = session - saveSession(session) - addOrUpdateSavedAccount(session) - return session.accessJwt + }; + state.session = session; + saveSession(session); + addOrUpdateSavedAccount(session); + return session.accessJwt; } catch { - return null + return null; } } export async function initAuth(): Promise<{ oauthLoginCompleted: boolean }> { - setTokenRefreshCallback(tryRefreshToken) - state.loading = true - state.error = null - state.savedAccounts = loadSavedAccounts() + setTokenRefreshCallback(tryRefreshToken); + state.loading = true; + state.error = null; + state.savedAccounts = loadSavedAccounts(); - const oauthCallback = checkForOAuthCallback() + const oauthCallback = checkForOAuthCallback(); if (oauthCallback) { - clearOAuthCallbackParams() + clearOAuthCallbackParams(); try { - const tokens = await handleOAuthCallback(oauthCallback.code, oauthCallback.state) - const sessionInfo = await api.getSession(tokens.access_token) + const tokens = await handleOAuthCallback( + oauthCallback.code, + oauthCallback.state, + ); + const sessionInfo = await api.getSession(tokens.access_token); const session: Session = { ...sessionInfo, accessJwt: tokens.access_token, - refreshJwt: tokens.refresh_token || '', - } - state.session = session - saveSession(session) - addOrUpdateSavedAccount(session) - applyLocaleFromSession(sessionInfo) - state.loading = false - return { oauthLoginCompleted: true } + refreshJwt: tokens.refresh_token || "", + }; + state.session = session; + saveSession(session); + addOrUpdateSavedAccount(session); + applyLocaleFromSession(sessionInfo); + state.loading = false; + return { oauthLoginCompleted: true }; } catch (e) { - state.error = e instanceof Error ? e.message : 'OAuth login failed' - state.loading = false - return { oauthLoginCompleted: false } + state.error = e instanceof Error ? e.message : "OAuth login failed"; + state.loading = false; + return { oauthLoginCompleted: false }; } } - const stored = loadSession() + const stored = loadSession(); if (stored) { try { - const sessionInfo = await api.getSession(stored.accessJwt) - state.session = { ...sessionInfo, accessJwt: stored.accessJwt, refreshJwt: stored.refreshJwt } - addOrUpdateSavedAccount(state.session) - applyLocaleFromSession(sessionInfo) + const sessionInfo = await api.getSession(stored.accessJwt); + state.session = { + ...sessionInfo, + accessJwt: stored.accessJwt, + refreshJwt: stored.refreshJwt, + }; + addOrUpdateSavedAccount(state.session); + applyLocaleFromSession(sessionInfo); } catch (e) { if (e instanceof ApiError && e.status === 401) { try { - const tokens = await refreshOAuthToken(stored.refreshJwt) - const sessionInfo = await api.getSession(tokens.access_token) + const tokens = await refreshOAuthToken(stored.refreshJwt); + const sessionInfo = await api.getSession(tokens.access_token); const session: Session = { ...sessionInfo, accessJwt: tokens.access_token, refreshJwt: tokens.refresh_token || stored.refreshJwt, - } - state.session = session - saveSession(session) - addOrUpdateSavedAccount(session) - applyLocaleFromSession(sessionInfo) + }; + state.session = session; + saveSession(session); + addOrUpdateSavedAccount(session); + applyLocaleFromSession(sessionInfo); } catch (refreshError) { - console.error('Token refresh failed during init:', refreshError) - saveSession(null) - state.session = null + console.error("Token refresh failed during init:", refreshError); + saveSession(null); + state.session = null; } } else { - console.error('Non-401 error during getSession:', e) - saveSession(null) - state.session = null + console.error("Non-401 error during getSession:", e); + saveSession(null); + state.session = null; } } } - state.loading = false - return { oauthLoginCompleted: false } + state.loading = false; + return { oauthLoginCompleted: false }; } -export async function login(identifier: string, password: string): Promise { - state.loading = true - state.error = null +export async function login( + identifier: string, + password: string, +): Promise { + state.loading = true; + state.error = null; try { - const session = await api.createSession(identifier, password) - state.session = session - saveSession(session) - addOrUpdateSavedAccount(session) + const session = await api.createSession(identifier, password); + state.session = session; + saveSession(session); + addOrUpdateSavedAccount(session); } catch (e) { if (e instanceof ApiError) { - state.error = e.message + state.error = e.message; } else { - state.error = 'Login failed' + state.error = "Login failed"; } - throw e + throw e; } finally { - state.loading = false + state.loading = false; } } export async function loginWithOAuth(): Promise { - state.loading = true - state.error = null + state.loading = true; + state.error = null; try { - await startOAuthLogin() + await startOAuthLogin(); } catch (e) { - state.loading = false - state.error = e instanceof Error ? e.message : 'Failed to start OAuth login' - throw e + state.loading = false; + state.error = e instanceof Error + ? e.message + : "Failed to start OAuth login"; + throw e; } } -export async function register(params: CreateAccountParams): Promise { +export async function register( + params: CreateAccountParams, +): Promise { try { - const result = await api.createAccount(params) - return result + const result = await api.createAccount(params); + return result; } catch (e) { if (e instanceof ApiError) { - state.error = e.message + state.error = e.message; } else { - state.error = 'Registration failed' + state.error = "Registration failed"; } - throw e + throw e; } } -export async function confirmSignup(did: string, verificationCode: string): Promise { - state.loading = true - state.error = null +export async function confirmSignup( + did: string, + verificationCode: string, +): Promise { + state.loading = true; + state.error = null; try { - const result = await api.confirmSignup(did, verificationCode) + const result = await api.confirmSignup(did, verificationCode); const session: Session = { did: result.did, handle: result.handle, @@ -238,167 +270,185 @@ export async function confirmSignup(did: string, verificationCode: string): Prom emailConfirmed: result.emailConfirmed, preferredChannel: result.preferredChannel, preferredChannelVerified: result.preferredChannelVerified, - } - state.session = session - saveSession(session) - addOrUpdateSavedAccount(session) + }; + state.session = session; + saveSession(session); + addOrUpdateSavedAccount(session); } catch (e) { if (e instanceof ApiError) { - state.error = e.message + state.error = e.message; } else { - state.error = 'Verification failed' + state.error = "Verification failed"; } - throw e + throw e; } finally { - state.loading = false + state.loading = false; } } export async function resendVerification(did: string): Promise { try { - await api.resendVerification(did) + await api.resendVerification(did); } catch (e) { if (e instanceof ApiError) { - throw e + throw e; } - throw new Error('Failed to resend verification code') + throw new Error("Failed to resend verification code"); } } -export function setSession(session: { did: string; handle: string; accessJwt: string; refreshJwt: string }): void { +export function setSession( + session: { + did: string; + handle: string; + accessJwt: string; + refreshJwt: string; + }, +): void { const newSession: Session = { did: session.did, handle: session.handle, accessJwt: session.accessJwt, refreshJwt: session.refreshJwt, - } - state.session = newSession - saveSession(newSession) - addOrUpdateSavedAccount(newSession) + }; + state.session = newSession; + saveSession(newSession); + addOrUpdateSavedAccount(newSession); } export async function logout(): Promise { if (state.session) { try { - await api.deleteSession(state.session.accessJwt) + await api.deleteSession(state.session.accessJwt); } catch { // Ignore errors on logout } } - state.session = null - saveSession(null) + state.session = null; + saveSession(null); } export async function switchAccount(did: string): Promise { - const account = state.savedAccounts.find(a => a.did === did) + const account = state.savedAccounts.find((a) => a.did === did); if (!account) { - throw new Error('Account not found') + throw new Error("Account not found"); } - state.loading = true - state.error = null + state.loading = true; + state.error = null; try { - const session = await api.getSession(account.accessJwt) - state.session = { ...session, accessJwt: account.accessJwt, refreshJwt: account.refreshJwt } - saveSession(state.session) - addOrUpdateSavedAccount(state.session) + const session = await api.getSession(account.accessJwt); + state.session = { + ...session, + accessJwt: account.accessJwt, + refreshJwt: account.refreshJwt, + }; + saveSession(state.session); + addOrUpdateSavedAccount(state.session); } catch (e) { if (e instanceof ApiError && e.status === 401) { try { - const tokens = await refreshOAuthToken(account.refreshJwt) - const sessionInfo = await api.getSession(tokens.access_token) + const tokens = await refreshOAuthToken(account.refreshJwt); + const sessionInfo = await api.getSession(tokens.access_token); const session: Session = { ...sessionInfo, accessJwt: tokens.access_token, refreshJwt: tokens.refresh_token || account.refreshJwt, - } - state.session = session - saveSession(session) - addOrUpdateSavedAccount(session) + }; + state.session = session; + saveSession(session); + addOrUpdateSavedAccount(session); } catch { - removeSavedAccount(did) - state.error = 'Session expired. Please log in again.' - throw new Error('Session expired') + removeSavedAccount(did); + state.error = "Session expired. Please log in again."; + throw new Error("Session expired"); } } else { - state.error = 'Failed to switch account' - throw e + state.error = "Failed to switch account"; + throw e; } } finally { - state.loading = false + state.loading = false; } } export function forgetAccount(did: string): void { - removeSavedAccount(did) + removeSavedAccount(did); } export function getAuthState() { - return state + return state; } export async function refreshSession(): Promise { - if (!state.session) return + if (!state.session) return; try { - const sessionInfo = await api.getSession(state.session.accessJwt) + const sessionInfo = await api.getSession(state.session.accessJwt); state.session = { ...sessionInfo, accessJwt: state.session.accessJwt, refreshJwt: state.session.refreshJwt, - } - saveSession(state.session) - addOrUpdateSavedAccount(state.session) + }; + saveSession(state.session); + addOrUpdateSavedAccount(state.session); } catch (e) { - console.error('Failed to refresh session:', e) + console.error("Failed to refresh session:", e); } } export function getToken(): string | null { - return state.session?.accessJwt ?? null + return state.session?.accessJwt ?? null; } export async function getValidToken(): Promise { - if (!state.session) return null + if (!state.session) return null; try { - await api.getSession(state.session.accessJwt) - return state.session.accessJwt + await api.getSession(state.session.accessJwt); + return state.session.accessJwt; } catch (e) { if (e instanceof ApiError && e.status === 401) { try { - const tokens = await refreshOAuthToken(state.session.refreshJwt) - const sessionInfo = await api.getSession(tokens.access_token) + const tokens = await refreshOAuthToken(state.session.refreshJwt); + const sessionInfo = await api.getSession(tokens.access_token); const session: Session = { ...sessionInfo, accessJwt: tokens.access_token, refreshJwt: tokens.refresh_token || state.session.refreshJwt, - } - state.session = session - saveSession(session) - addOrUpdateSavedAccount(session) - return session.accessJwt + }; + state.session = session; + saveSession(session); + addOrUpdateSavedAccount(session); + return session.accessJwt; } catch { - return null + return null; } } - return null + return null; } } export function isAuthenticated(): boolean { - return state.session !== null + return state.session !== null; } -export function _testSetState(newState: { session: Session | null; loading: boolean; error: string | null; savedAccounts?: SavedAccount[] }) { - state.session = newState.session - state.loading = newState.loading - state.error = newState.error - state.savedAccounts = newState.savedAccounts ?? [] +export function _testSetState( + newState: { + session: Session | null; + loading: boolean; + error: string | null; + savedAccounts?: SavedAccount[]; + }, +) { + state.session = newState.session; + state.loading = newState.loading; + state.error = newState.error; + state.savedAccounts = newState.savedAccounts ?? []; } export function _testReset() { - state.session = null - state.loading = true - state.error = null - state.savedAccounts = [] - localStorage.removeItem(STORAGE_KEY) - localStorage.removeItem(ACCOUNTS_KEY) + state.session = null; + state.loading = true; + state.error = null; + state.savedAccounts = []; + localStorage.removeItem(STORAGE_KEY); + localStorage.removeItem(ACCOUNTS_KEY); } diff --git a/frontend/src/lib/crypto.ts b/frontend/src/lib/crypto.ts index d3ca6e3..ba55830 100644 --- a/frontend/src/lib/crypto.ts +++ b/frontend/src/lib/crypto.ts @@ -1,55 +1,59 @@ -import * as secp from '@noble/secp256k1' -import { base58btc } from 'multiformats/bases/base58' +import * as secp from "@noble/secp256k1"; +import { base58btc } from "multiformats/bases/base58"; -const SECP256K1_MULTICODEC_PREFIX = new Uint8Array([0xe7, 0x01]) +const SECP256K1_MULTICODEC_PREFIX = new Uint8Array([0xe7, 0x01]); export interface Keypair { - privateKey: Uint8Array - publicKey: Uint8Array - publicKeyMultibase: string - publicKeyDidKey: string + privateKey: Uint8Array; + publicKey: Uint8Array; + publicKeyMultibase: string; + publicKeyDidKey: string; } export async function generateKeypair(): Promise { - const privateKey = secp.utils.randomPrivateKey() - const publicKey = secp.getPublicKey(privateKey, true) + const privateKey = secp.utils.randomPrivateKey(); + const publicKey = secp.getPublicKey(privateKey, true); - const multicodecKey = new Uint8Array(SECP256K1_MULTICODEC_PREFIX.length + publicKey.length) - multicodecKey.set(SECP256K1_MULTICODEC_PREFIX, 0) - multicodecKey.set(publicKey, SECP256K1_MULTICODEC_PREFIX.length) + const multicodecKey = new Uint8Array( + SECP256K1_MULTICODEC_PREFIX.length + publicKey.length, + ); + multicodecKey.set(SECP256K1_MULTICODEC_PREFIX, 0); + multicodecKey.set(publicKey, SECP256K1_MULTICODEC_PREFIX.length); - const publicKeyMultibase = base58btc.encode(multicodecKey) - const publicKeyDidKey = `did:key:${publicKeyMultibase}` + const publicKeyMultibase = base58btc.encode(multicodecKey); + const publicKeyDidKey = `did:key:${publicKeyMultibase}`; return { privateKey, publicKey, publicKeyMultibase, publicKeyDidKey, - } + }; } function base64UrlEncode(data: Uint8Array | string): string { - const bytes = typeof data === 'string' ? new TextEncoder().encode(data) : data - let binary = '' + const bytes = typeof data === "string" + ? new TextEncoder().encode(data) + : data; + let binary = ""; for (let i = 0; i < bytes.length; i++) { - binary += String.fromCharCode(bytes[i]) + binary += String.fromCharCode(bytes[i]); } - return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '') + return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, ""); } export async function createServiceJwt( privateKey: Uint8Array, issuerDid: string, audienceDid: string, - lxm: string + lxm: string, ): Promise { const header = { - alg: 'ES256K', - typ: 'JWT', - } + alg: "ES256K", + typ: "JWT", + }; - const now = Math.floor(Date.now() / 1000) + const now = Math.floor(Date.now() / 1000); const payload = { iss: issuerDid, sub: issuerDid, @@ -57,50 +61,50 @@ export async function createServiceJwt( exp: now + 180, iat: now, lxm: lxm, - } + }; - const headerEncoded = base64UrlEncode(JSON.stringify(header)) - const payloadEncoded = base64UrlEncode(JSON.stringify(payload)) - const message = `${headerEncoded}.${payloadEncoded}` + const headerEncoded = base64UrlEncode(JSON.stringify(header)); + const payloadEncoded = base64UrlEncode(JSON.stringify(payload)); + const message = `${headerEncoded}.${payloadEncoded}`; - const msgBytes = new TextEncoder().encode(message) - const hashBuffer = await crypto.subtle.digest('SHA-256', msgBytes) - const msgHash = new Uint8Array(hashBuffer) - const signature = await secp.signAsync(msgHash, privateKey) - const sigBytes = signature.toCompactRawBytes() - const signatureEncoded = base64UrlEncode(sigBytes) + const msgBytes = new TextEncoder().encode(message); + const hashBuffer = await crypto.subtle.digest("SHA-256", msgBytes); + const msgHash = new Uint8Array(hashBuffer); + const signature = await secp.signAsync(msgHash, privateKey); + const sigBytes = signature.toCompactRawBytes(); + const signatureEncoded = base64UrlEncode(sigBytes); - return `${message}.${signatureEncoded}` + return `${message}.${signatureEncoded}`; } export function generateDidDocument( did: string, publicKeyMultibase: string, handle: string, - pdsEndpoint: string + pdsEndpoint: string, ): object { return { - '@context': [ - 'https://www.w3.org/ns/did/v1', - 'https://w3id.org/security/multikey/v1', - 'https://w3id.org/security/suites/secp256k1-2019/v1', + "@context": [ + "https://www.w3.org/ns/did/v1", + "https://w3id.org/security/multikey/v1", + "https://w3id.org/security/suites/secp256k1-2019/v1", ], id: did, alsoKnownAs: [`at://${handle}`], verificationMethod: [ { id: `${did}#atproto`, - type: 'Multikey', + type: "Multikey", controller: did, publicKeyMultibase: publicKeyMultibase, }, ], service: [ { - id: '#atproto_pds', - type: 'AtprotoPersonalDataServer', + id: "#atproto_pds", + type: "AtprotoPersonalDataServer", serviceEndpoint: pdsEndpoint, }, ], - } + }; } diff --git a/frontend/src/lib/date.ts b/frontend/src/lib/date.ts index 07f13a2..19aa107 100644 --- a/frontend/src/lib/date.ts +++ b/frontend/src/lib/date.ts @@ -1,17 +1,17 @@ export function formatDate(dateStr: string): string { - const date = new Date(dateStr) - const year = date.getFullYear() - const month = String(date.getMonth() + 1).padStart(2, '0') - const day = String(date.getDate()).padStart(2, '0') - return `${year}-${month}-${day}` + const date = new Date(dateStr); + const year = date.getFullYear(); + const month = String(date.getMonth() + 1).padStart(2, "0"); + const day = String(date.getDate()).padStart(2, "0"); + return `${year}-${month}-${day}`; } export function formatDateTime(dateStr: string): string { - const date = new Date(dateStr) - const year = date.getFullYear() - const month = String(date.getMonth() + 1).padStart(2, '0') - const day = String(date.getDate()).padStart(2, '0') - const hours = String(date.getHours()).padStart(2, '0') - const minutes = String(date.getMinutes()).padStart(2, '0') - return `${year}-${month}-${day} ${hours}:${minutes}` + const date = new Date(dateStr); + const year = date.getFullYear(); + const month = String(date.getMonth() + 1).padStart(2, "0"); + const day = String(date.getDate()).padStart(2, "0"); + const hours = String(date.getHours()).padStart(2, "0"); + const minutes = String(date.getMinutes()).padStart(2, "0"); + return `${year}-${month}-${day} ${hours}:${minutes}`; } diff --git a/frontend/src/lib/i18n.ts b/frontend/src/lib/i18n.ts index 6db2056..238f95b 100644 --- a/frontend/src/lib/i18n.ts +++ b/frontend/src/lib/i18n.ts @@ -1,58 +1,58 @@ -import { register, init, getLocaleFromNavigator, locale, _ } from 'svelte-i18n' +import { _, getLocaleFromNavigator, init, locale, register } from "svelte-i18n"; -const LOCALE_STORAGE_KEY = 'tranquil-pds-locale' +const LOCALE_STORAGE_KEY = "tranquil-pds-locale"; -const SUPPORTED_LOCALES = ['en', 'zh', 'ja', 'ko', 'sv', 'fi'] as const -export type SupportedLocale = typeof SUPPORTED_LOCALES[number] +const SUPPORTED_LOCALES = ["en", "zh", "ja", "ko", "sv", "fi"] as const; +export type SupportedLocale = typeof SUPPORTED_LOCALES[number]; export const localeNames: Record = { - en: 'English', - zh: '中文', - ja: '日本語', - ko: '한국어', - sv: 'Svenska', - fi: 'Suomi' -} + en: "English", + zh: "中文", + ja: "日本語", + ko: "한국어", + sv: "Svenska", + fi: "Suomi", +}; -register('en', () => import('../locales/en.json')) -register('zh', () => import('../locales/zh.json')) -register('ja', () => import('../locales/ja.json')) -register('ko', () => import('../locales/ko.json')) -register('sv', () => import('../locales/sv.json')) -register('fi', () => import('../locales/fi.json')) +register("en", () => import("../locales/en.json")); +register("zh", () => import("../locales/zh.json")); +register("ja", () => import("../locales/ja.json")); +register("ko", () => import("../locales/ko.json")); +register("sv", () => import("../locales/sv.json")); +register("fi", () => import("../locales/fi.json")); function getInitialLocale(): string { - const stored = localStorage.getItem(LOCALE_STORAGE_KEY) + const stored = localStorage.getItem(LOCALE_STORAGE_KEY); if (stored && SUPPORTED_LOCALES.includes(stored as SupportedLocale)) { - return stored + return stored; } - const browserLocale = getLocaleFromNavigator() + const browserLocale = getLocaleFromNavigator(); if (browserLocale) { - const lang = browserLocale.split('-')[0] + const lang = browserLocale.split("-")[0]; if (SUPPORTED_LOCALES.includes(lang as SupportedLocale)) { - return lang + return lang; } } - return 'en' + return "en"; } export function initI18n() { init({ - fallbackLocale: 'en', - initialLocale: getInitialLocale() - }) + fallbackLocale: "en", + initialLocale: getInitialLocale(), + }); } export function setLocale(newLocale: SupportedLocale) { - locale.set(newLocale) - localStorage.setItem(LOCALE_STORAGE_KEY, newLocale) - document.documentElement.lang = newLocale + locale.set(newLocale); + localStorage.setItem(LOCALE_STORAGE_KEY, newLocale); + document.documentElement.lang = newLocale; } export function getSupportedLocales(): SupportedLocale[] { - return [...SUPPORTED_LOCALES] + return [...SUPPORTED_LOCALES]; } -export { locale, _ } +export { _, locale }; diff --git a/frontend/src/lib/oauth.ts b/frontend/src/lib/oauth.ts index b21b51c..df40ec1 100644 --- a/frontend/src/lib/oauth.ts +++ b/frontend/src/lib/oauth.ts @@ -1,184 +1,209 @@ -const OAUTH_STATE_KEY = 'tranquil_pds_oauth_state' -const OAUTH_VERIFIER_KEY = 'tranquil_pds_oauth_verifier' +const OAUTH_STATE_KEY = "tranquil_pds_oauth_state"; +const OAUTH_VERIFIER_KEY = "tranquil_pds_oauth_verifier"; const SCOPES = [ - 'atproto', - 'repo:*?action=create', - 'repo:*?action=update', - 'repo:*?action=delete', - 'blob:*/*', -].join(' ') + "atproto", + "repo:*?action=create", + "repo:*?action=update", + "repo:*?action=delete", + "blob:*/*", +].join(" "); const CLIENT_ID = !(import.meta.env.DEV) - ? `${window.location.origin}/oauth/client-metadata.json` - : `http://localhost/?scope=${SCOPES}` -const REDIRECT_URI = `${window.location.origin}/` + ? `${window.location.origin}/oauth/client-metadata.json` + : `http://localhost/?scope=${SCOPES}`; +const REDIRECT_URI = `${window.location.origin}/`; interface OAuthState { - state: string - codeVerifier: string - returnTo?: string + state: string; + codeVerifier: string; + returnTo?: string; } function generateRandomString(length: number): string { - const array = new Uint8Array(length) - crypto.getRandomValues(array) - return Array.from(array, (byte) => byte.toString(16).padStart(2, '0')).join('') + const array = new Uint8Array(length); + crypto.getRandomValues(array); + return Array.from(array, (byte) => byte.toString(16).padStart(2, "0")).join( + "", + ); } async function sha256(plain: string): Promise { - const encoder = new TextEncoder() - const data = encoder.encode(plain) - return crypto.subtle.digest('SHA-256', data) + const encoder = new TextEncoder(); + const data = encoder.encode(plain); + return crypto.subtle.digest("SHA-256", data); } function base64UrlEncode(buffer: ArrayBuffer): string { - const bytes = new Uint8Array(buffer) - let binary = '' + const bytes = new Uint8Array(buffer); + let binary = ""; for (const byte of bytes) { - binary += String.fromCharCode(byte) + binary += String.fromCharCode(byte); } - return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '') + return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace( + /=+$/, + "", + ); } async function generateCodeChallenge(verifier: string): Promise { - const hash = await sha256(verifier) - return base64UrlEncode(hash) + const hash = await sha256(verifier); + return base64UrlEncode(hash); } function generateState(): string { - return generateRandomString(32) + return generateRandomString(32); } function generateCodeVerifier(): string { - return generateRandomString(32) + return generateRandomString(32); } function saveOAuthState(state: OAuthState): void { - sessionStorage.setItem(OAUTH_STATE_KEY, state.state) - sessionStorage.setItem(OAUTH_VERIFIER_KEY, state.codeVerifier) + sessionStorage.setItem(OAUTH_STATE_KEY, state.state); + sessionStorage.setItem(OAUTH_VERIFIER_KEY, state.codeVerifier); } function getOAuthState(): OAuthState | null { - const state = sessionStorage.getItem(OAUTH_STATE_KEY) - const codeVerifier = sessionStorage.getItem(OAUTH_VERIFIER_KEY) - if (!state || !codeVerifier) return null - return { state, codeVerifier } + const state = sessionStorage.getItem(OAUTH_STATE_KEY); + const codeVerifier = sessionStorage.getItem(OAUTH_VERIFIER_KEY); + if (!state || !codeVerifier) return null; + return { state, codeVerifier }; } function clearOAuthState(): void { - sessionStorage.removeItem(OAUTH_STATE_KEY) - sessionStorage.removeItem(OAUTH_VERIFIER_KEY) + sessionStorage.removeItem(OAUTH_STATE_KEY); + sessionStorage.removeItem(OAUTH_VERIFIER_KEY); } export async function startOAuthLogin(): Promise { - const state = generateState() - const codeVerifier = generateCodeVerifier() - const codeChallenge = await generateCodeChallenge(codeVerifier) + const state = generateState(); + const codeVerifier = generateCodeVerifier(); + const codeChallenge = await generateCodeChallenge(codeVerifier); - saveOAuthState({ state, codeVerifier }) + saveOAuthState({ state, codeVerifier }); - const parResponse = await fetch('/oauth/par', { - method: 'POST', - headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, + const parResponse = await fetch("/oauth/par", { + method: "POST", + headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: new URLSearchParams({ client_id: CLIENT_ID, redirect_uri: REDIRECT_URI, - response_type: 'code', + response_type: "code", scope: SCOPES, state: state, code_challenge: codeChallenge, - code_challenge_method: 'S256', + code_challenge_method: "S256", }), - }) + }); if (!parResponse.ok) { - const error = await parResponse.json().catch(() => ({ error: 'Unknown error' })) - throw new Error(error.error_description || error.error || 'Failed to start OAuth flow') + const error = await parResponse.json().catch(() => ({ + error: "Unknown error", + })); + throw new Error( + error.error_description || error.error || "Failed to start OAuth flow", + ); } - const { request_uri } = await parResponse.json() + const { request_uri } = await parResponse.json(); - const authorizeUrl = new URL('/oauth/authorize', window.location.origin) - authorizeUrl.searchParams.set('client_id', CLIENT_ID) - authorizeUrl.searchParams.set('request_uri', request_uri) + const authorizeUrl = new URL("/oauth/authorize", window.location.origin); + authorizeUrl.searchParams.set("client_id", CLIENT_ID); + authorizeUrl.searchParams.set("request_uri", request_uri); - window.location.href = authorizeUrl.toString() + window.location.href = authorizeUrl.toString(); } export interface OAuthTokens { - access_token: string - refresh_token?: string - token_type: string - expires_in?: number - scope?: string - sub: string + access_token: string; + refresh_token?: string; + token_type: string; + expires_in?: number; + scope?: string; + sub: string; } -export async function handleOAuthCallback(code: string, state: string): Promise { - const savedState = getOAuthState() +export async function handleOAuthCallback( + code: string, + state: string, +): Promise { + const savedState = getOAuthState(); if (!savedState) { - throw new Error('No OAuth state found. Please try logging in again.') + throw new Error("No OAuth state found. Please try logging in again."); } if (savedState.state !== state) { - clearOAuthState() - throw new Error('OAuth state mismatch. Please try logging in again.') + clearOAuthState(); + throw new Error("OAuth state mismatch. Please try logging in again."); } - const tokenResponse = await fetch('/oauth/token', { - method: 'POST', - headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, + const tokenResponse = await fetch("/oauth/token", { + method: "POST", + headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: new URLSearchParams({ - grant_type: 'authorization_code', + grant_type: "authorization_code", client_id: CLIENT_ID, code: code, redirect_uri: REDIRECT_URI, code_verifier: savedState.codeVerifier, }), - }) + }); - clearOAuthState() + clearOAuthState(); if (!tokenResponse.ok) { - const error = await tokenResponse.json().catch(() => ({ error: 'Unknown error' })) - throw new Error(error.error_description || error.error || 'Failed to exchange code for tokens') + const error = await tokenResponse.json().catch(() => ({ + error: "Unknown error", + })); + throw new Error( + error.error_description || error.error || + "Failed to exchange code for tokens", + ); } - return tokenResponse.json() + return tokenResponse.json(); } -export async function refreshOAuthToken(refreshToken: string): Promise { - const tokenResponse = await fetch('/oauth/token', { - method: 'POST', - headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, +export async function refreshOAuthToken( + refreshToken: string, +): Promise { + const tokenResponse = await fetch("/oauth/token", { + method: "POST", + headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: new URLSearchParams({ - grant_type: 'refresh_token', + grant_type: "refresh_token", client_id: CLIENT_ID, refresh_token: refreshToken, }), - }) + }); if (!tokenResponse.ok) { - const error = await tokenResponse.json().catch(() => ({ error: 'Unknown error' })) - throw new Error(error.error_description || error.error || 'Failed to refresh token') + const error = await tokenResponse.json().catch(() => ({ + error: "Unknown error", + })); + throw new Error( + error.error_description || error.error || "Failed to refresh token", + ); } - return tokenResponse.json() + return tokenResponse.json(); } -export function checkForOAuthCallback(): { code: string; state: string } | null { - const params = new URLSearchParams(window.location.search) - const code = params.get('code') - const state = params.get('state') +export function checkForOAuthCallback(): + | { code: string; state: string } + | null { + const params = new URLSearchParams(window.location.search); + const code = params.get("code"); + const state = params.get("state"); if (code && state) { - return { code, state } + return { code, state }; } - return null + return null; } export function clearOAuthCallbackParams(): void { - const url = new URL(window.location.href) - url.search = '' - window.history.replaceState({}, '', url.toString()) + const url = new URL(window.location.href); + url.search = ""; + window.history.replaceState({}, "", url.toString()); } diff --git a/frontend/src/lib/registration/flow.svelte.ts b/frontend/src/lib/registration/flow.svelte.ts index 6c003e2..bca3317 100644 --- a/frontend/src/lib/registration/flow.svelte.ts +++ b/frontend/src/lib/registration/flow.svelte.ts @@ -1,139 +1,157 @@ -import { api, ApiError } from '../api' -import { generateKeypair, createServiceJwt, generateDidDocument } from '../crypto' +import { api, ApiError } from "../api"; +import { + createServiceJwt, + generateDidDocument, + generateKeypair, +} from "../crypto"; import type { + AccountResult, + ExternalDidWebState, + RegistrationInfo, RegistrationMode, RegistrationStep, - RegistrationInfo, - ExternalDidWebState, - AccountResult, SessionState, -} from './types' +} from "./types"; export interface RegistrationFlowState { - mode: RegistrationMode - step: RegistrationStep - info: RegistrationInfo - externalDidWeb: ExternalDidWebState - account: AccountResult | null - session: SessionState | null - error: string | null - submitting: boolean - pdsHostname: string + mode: RegistrationMode; + step: RegistrationStep; + info: RegistrationInfo; + externalDidWeb: ExternalDidWebState; + account: AccountResult | null; + session: SessionState | null; + error: string | null; + submitting: boolean; + pdsHostname: string; } -export function createRegistrationFlow(mode: RegistrationMode, pdsHostname: string) { +export function createRegistrationFlow( + mode: RegistrationMode, + pdsHostname: string, +) { let state = $state({ mode, - step: 'info', + step: "info", info: { - handle: '', - email: '', - password: '', - inviteCode: '', - didType: 'plc', - externalDid: '', - verificationChannel: 'email', - discordId: '', - telegramUsername: '', - signalNumber: '', + handle: "", + email: "", + password: "", + inviteCode: "", + didType: "plc", + externalDid: "", + verificationChannel: "email", + discordId: "", + telegramUsername: "", + signalNumber: "", }, externalDidWeb: { - keyMode: 'reserved', + keyMode: "reserved", }, account: null, session: null, error: null, submitting: false, pdsHostname, - }) + }); function getPdsEndpoint(): string { - return `https://${state.pdsHostname}` + return `https://${state.pdsHostname}`; } function getPdsDid(): string { - return `did:web:${state.pdsHostname}` + return `did:web:${state.pdsHostname}`; } function getFullHandle(): string { - return `${state.info.handle.trim()}.${state.pdsHostname}` + return `${state.info.handle.trim()}.${state.pdsHostname}`; } function extractDomain(did: string): string { - return did.replace('did:web:', '').replace(/%3A/g, ':') + return did.replace("did:web:", "").replace(/%3A/g, ":"); } function setError(err: unknown) { if (err instanceof ApiError) { - state.error = err.message || 'An error occurred' + state.error = err.message || "An error occurred"; } else if (err instanceof Error) { - state.error = err.message || 'An error occurred' + state.error = err.message || "An error occurred"; } else { - state.error = 'An error occurred' + state.error = "An error occurred"; } } async function proceedFromInfo() { - state.error = null - if (state.info.didType === 'web-external') { - state.step = 'key-choice' + state.error = null; + if (state.info.didType === "web-external") { + state.step = "key-choice"; } else { - state.step = 'creating' + state.step = "creating"; } } - async function selectKeyMode(keyMode: 'reserved' | 'byod') { - state.submitting = true - state.error = null - state.externalDidWeb.keyMode = keyMode + async function selectKeyMode(keyMode: "reserved" | "byod") { + state.submitting = true; + state.error = null; + state.externalDidWeb.keyMode = keyMode; try { - let publicKeyMultibase: string + let publicKeyMultibase: string; - if (keyMode === 'reserved') { - const result = await api.reserveSigningKey(state.info.externalDid!.trim()) - state.externalDidWeb.reservedSigningKey = result.signingKey - publicKeyMultibase = result.signingKey.replace('did:key:', '') + if (keyMode === "reserved") { + const result = await api.reserveSigningKey( + state.info.externalDid!.trim(), + ); + state.externalDidWeb.reservedSigningKey = result.signingKey; + publicKeyMultibase = result.signingKey.replace("did:key:", ""); } else { - const keypair = await generateKeypair() - state.externalDidWeb.byodPrivateKey = keypair.privateKey - state.externalDidWeb.byodPublicKeyMultibase = keypair.publicKeyMultibase - publicKeyMultibase = keypair.publicKeyMultibase + const keypair = await generateKeypair(); + state.externalDidWeb.byodPrivateKey = keypair.privateKey; + state.externalDidWeb.byodPublicKeyMultibase = + keypair.publicKeyMultibase; + publicKeyMultibase = keypair.publicKeyMultibase; } const didDoc = generateDidDocument( state.info.externalDid!.trim(), publicKeyMultibase, getFullHandle(), - getPdsEndpoint() - ) - state.externalDidWeb.initialDidDocument = JSON.stringify(didDoc, null, '\t') - state.step = 'initial-did-doc' + getPdsEndpoint(), + ); + state.externalDidWeb.initialDidDocument = JSON.stringify( + didDoc, + null, + "\t", + ); + state.step = "initial-did-doc"; } catch (err) { - setError(err) + setError(err); } finally { - state.submitting = false + state.submitting = false; } } async function confirmInitialDidDoc() { - state.step = 'creating' + state.step = "creating"; } async function createPasswordAccount() { - state.submitting = true - state.error = null + state.submitting = true; + state.error = null; try { - let byodToken: string | undefined + let byodToken: string | undefined; - if (state.info.didType === 'web-external' && state.externalDidWeb.keyMode === 'byod' && state.externalDidWeb.byodPrivateKey) { + if ( + state.info.didType === "web-external" && + state.externalDidWeb.keyMode === "byod" && + state.externalDidWeb.byodPrivateKey + ) { byodToken = await createServiceJwt( state.externalDidWeb.byodPrivateKey, state.info.externalDid!.trim(), getPdsDid(), - 'com.atproto.server.createAccount' - ) + "com.atproto.server.createAccount", + ); } const result = await api.createAccount({ @@ -142,42 +160,49 @@ export function createRegistrationFlow(mode: RegistrationMode, pdsHostname: stri password: state.info.password!, inviteCode: state.info.inviteCode?.trim() || undefined, didType: state.info.didType, - did: state.info.didType === 'web-external' ? state.info.externalDid!.trim() : undefined, - signingKey: state.info.didType === 'web-external' && state.externalDidWeb.keyMode === 'reserved' + did: state.info.didType === "web-external" + ? state.info.externalDid!.trim() + : undefined, + signingKey: state.info.didType === "web-external" && + state.externalDidWeb.keyMode === "reserved" ? state.externalDidWeb.reservedSigningKey : undefined, verificationChannel: state.info.verificationChannel, discordId: state.info.discordId?.trim() || undefined, telegramUsername: state.info.telegramUsername?.trim() || undefined, signalNumber: state.info.signalNumber?.trim() || undefined, - }, byodToken) + }, byodToken); state.account = { did: result.did, handle: result.handle, - } - state.step = 'verify' + }; + state.step = "verify"; } catch (err) { - setError(err) + setError(err); } finally { - state.submitting = false + state.submitting = false; } } async function createPasskeyAccount() { - state.submitting = true - state.error = null + state.submitting = true; + state.error = null; try { - let byodToken: string | undefined + let byodToken: string | undefined; - if (state.info.didType === 'web-external' && state.externalDidWeb.keyMode === 'byod' && state.externalDidWeb.byodPrivateKey) { + if ( + state.info.didType === "web-external" && + state.externalDidWeb.keyMode === "byod" && + state.externalDidWeb.byodPrivateKey + ) { byodToken = await createServiceJwt( state.externalDidWeb.byodPrivateKey, state.info.externalDid!.trim(), getPdsDid(), - 'com.atproto.server.createAccount' - ) + "com.atproto.server.createAccount", + ); } const result = await api.createPasskeyAccount({ @@ -185,134 +210,162 @@ export function createRegistrationFlow(mode: RegistrationMode, pdsHostname: stri email: state.info.email?.trim() || undefined, inviteCode: state.info.inviteCode?.trim() || undefined, didType: state.info.didType, - did: state.info.didType === 'web-external' ? state.info.externalDid!.trim() : undefined, - signingKey: state.info.didType === 'web-external' && state.externalDidWeb.keyMode === 'reserved' + did: state.info.didType === "web-external" + ? state.info.externalDid!.trim() + : undefined, + signingKey: state.info.didType === "web-external" && + state.externalDidWeb.keyMode === "reserved" ? state.externalDidWeb.reservedSigningKey : undefined, verificationChannel: state.info.verificationChannel, discordId: state.info.discordId?.trim() || undefined, telegramUsername: state.info.telegramUsername?.trim() || undefined, signalNumber: state.info.signalNumber?.trim() || undefined, - }, byodToken) + }, byodToken); state.account = { did: result.did, handle: result.handle, setupToken: result.setupToken, - } - state.step = 'passkey' + }; + state.step = "passkey"; } catch (err) { - setError(err) + setError(err); } finally { - state.submitting = false + state.submitting = false; } } function setPasskeyComplete(appPassword: string, appPasswordName: string) { if (state.account) { - state.account.appPassword = appPassword - state.account.appPasswordName = appPasswordName + state.account.appPassword = appPassword; + state.account.appPasswordName = appPasswordName; } - state.step = 'app-password' + state.step = "app-password"; } function proceedFromAppPassword() { - state.step = 'verify' + state.step = "verify"; } async function verifyAccount(code: string) { - state.submitting = true - state.error = null + state.submitting = true; + state.error = null; try { - const confirmResult = await api.confirmSignup(state.account!.did, code.trim()) + const confirmResult = await api.confirmSignup( + state.account!.did, + code.trim(), + ); - if (state.info.didType === 'web-external') { - const password = state.mode === 'passkey' ? state.account!.appPassword! : state.info.password! - const session = await api.createSession(state.account!.did, password) + if (state.info.didType === "web-external") { + const password = state.mode === "passkey" + ? state.account!.appPassword! + : state.info.password!; + const session = await api.createSession(state.account!.did, password); state.session = { accessJwt: session.accessJwt, refreshJwt: session.refreshJwt, - } + }; - if (state.externalDidWeb.keyMode === 'byod') { - const credentials = await api.getRecommendedDidCredentials(session.accessJwt) - const newPublicKeyMultibase = credentials.verificationMethods?.atproto?.replace('did:key:', '') || '' + if (state.externalDidWeb.keyMode === "byod") { + const credentials = await api.getRecommendedDidCredentials( + session.accessJwt, + ); + const newPublicKeyMultibase = + credentials.verificationMethods?.atproto?.replace("did:key:", "") || + ""; const didDoc = generateDidDocument( state.info.externalDid!.trim(), newPublicKeyMultibase, state.account!.handle, - getPdsEndpoint() - ) - state.externalDidWeb.updatedDidDocument = JSON.stringify(didDoc, null, '\t') - state.step = 'updated-did-doc' + getPdsEndpoint(), + ); + state.externalDidWeb.updatedDidDocument = JSON.stringify( + didDoc, + null, + "\t", + ); + state.step = "updated-did-doc"; } else { - await api.activateAccount(session.accessJwt) - await finalizeSession() - state.step = 'redirect-to-dashboard' + await api.activateAccount(session.accessJwt); + await finalizeSession(); + state.step = "redirect-to-dashboard"; } } else { state.session = { accessJwt: confirmResult.accessJwt, refreshJwt: confirmResult.refreshJwt, - } - await finalizeSession() - state.step = 'redirect-to-dashboard' + }; + await finalizeSession(); + state.step = "redirect-to-dashboard"; } } catch (err) { - setError(err) + setError(err); } finally { - state.submitting = false + state.submitting = false; } } async function activateAccount() { - state.submitting = true - state.error = null + state.submitting = true; + state.error = null; try { - await api.activateAccount(state.session!.accessJwt) - await finalizeSession() - state.step = 'redirect-to-dashboard' + await api.activateAccount(state.session!.accessJwt); + await finalizeSession(); + state.step = "redirect-to-dashboard"; } catch (err) { - setError(err) + setError(err); } finally { - state.submitting = false + state.submitting = false; } } function goBack() { switch (state.step) { - case 'key-choice': - state.step = 'info' - break - case 'initial-did-doc': - state.step = 'key-choice' - break - case 'passkey': - state.step = state.info.didType === 'web-external' ? 'initial-did-doc' : 'info' - break + case "key-choice": + state.step = "info"; + break; + case "initial-did-doc": + state.step = "key-choice"; + break; + case "passkey": + state.step = state.info.didType === "web-external" + ? "initial-did-doc" + : "info"; + break; } } async function finalizeSession() { - if (!state.session || !state.account) return - const { setSession } = await import('../auth.svelte') + if (!state.session || !state.account) return; + const { setSession } = await import("../auth.svelte"); setSession({ did: state.account.did, handle: state.account.handle, accessJwt: state.session.accessJwt, refreshJwt: state.session.refreshJwt, - }) + }); } return { - get state() { return state }, - get info() { return state.info }, - get externalDidWeb() { return state.externalDidWeb }, - get account() { return state.account }, - get session() { return state.session }, + get state() { + return state; + }, + get info() { + return state.info; + }, + get externalDidWeb() { + return state.externalDidWeb; + }, + get account() { + return state.account; + }, + get session() { + return state.session; + }, getPdsEndpoint, getPdsDid, @@ -331,10 +384,16 @@ export function createRegistrationFlow(mode: RegistrationMode, pdsHostname: stri finalizeSession, goBack, - setError(msg: string) { state.error = msg }, - clearError() { state.error = null }, - setSubmitting(val: boolean) { state.submitting = val }, - } + setError(msg: string) { + state.error = msg; + }, + clearError() { + state.error = null; + }, + setSubmitting(val: boolean) { + state.submitting = val; + }, + }; } -export type RegistrationFlow = ReturnType +export type RegistrationFlow = ReturnType; diff --git a/frontend/src/lib/registration/index.ts b/frontend/src/lib/registration/index.ts index 7358637..c80e389 100644 --- a/frontend/src/lib/registration/index.ts +++ b/frontend/src/lib/registration/index.ts @@ -1,6 +1,6 @@ -export * from './types' -export * from './flow.svelte' -export { default as VerificationStep } from './VerificationStep.svelte' -export { default as KeyChoiceStep } from './KeyChoiceStep.svelte' -export { default as DidDocStep } from './DidDocStep.svelte' -export { default as AppPasswordStep } from './AppPasswordStep.svelte' +export * from "./types"; +export * from "./flow.svelte"; +export { default as VerificationStep } from "./VerificationStep.svelte"; +export { default as KeyChoiceStep } from "./KeyChoiceStep.svelte"; +export { default as DidDocStep } from "./DidDocStep.svelte"; +export { default as AppPasswordStep } from "./AppPasswordStep.svelte"; diff --git a/frontend/src/lib/registration/types.ts b/frontend/src/lib/registration/types.ts index 1733b25..2c0e9f9 100644 --- a/frontend/src/lib/registration/types.ts +++ b/frontend/src/lib/registration/types.ts @@ -1,50 +1,50 @@ -import type { VerificationChannel, DidType } from '../api' +import type { DidType, VerificationChannel } from "../api"; -export type RegistrationMode = 'password' | 'passkey' +export type RegistrationMode = "password" | "passkey"; export type RegistrationStep = - | 'info' - | 'key-choice' - | 'initial-did-doc' - | 'creating' - | 'passkey' - | 'app-password' - | 'verify' - | 'updated-did-doc' - | 'activating' - | 'redirect-to-dashboard' + | "info" + | "key-choice" + | "initial-did-doc" + | "creating" + | "passkey" + | "app-password" + | "verify" + | "updated-did-doc" + | "activating" + | "redirect-to-dashboard"; export interface RegistrationInfo { - handle: string - email: string - password?: string - inviteCode?: string - didType: DidType - externalDid?: string - verificationChannel: VerificationChannel - discordId?: string - telegramUsername?: string - signalNumber?: string + handle: string; + email: string; + password?: string; + inviteCode?: string; + didType: DidType; + externalDid?: string; + verificationChannel: VerificationChannel; + discordId?: string; + telegramUsername?: string; + signalNumber?: string; } export interface ExternalDidWebState { - keyMode: 'reserved' | 'byod' - reservedSigningKey?: string - byodPrivateKey?: Uint8Array - byodPublicKeyMultibase?: string - initialDidDocument?: string - updatedDidDocument?: string + keyMode: "reserved" | "byod"; + reservedSigningKey?: string; + byodPrivateKey?: Uint8Array; + byodPublicKeyMultibase?: string; + initialDidDocument?: string; + updatedDidDocument?: string; } export interface AccountResult { - did: string - handle: string - setupToken?: string - appPassword?: string - appPasswordName?: string + did: string; + handle: string; + setupToken?: string; + appPassword?: string; + appPasswordName?: string; } export interface SessionState { - accessJwt: string - refreshJwt: string + accessJwt: string; + refreshJwt: string; } diff --git a/frontend/src/lib/router.svelte.ts b/frontend/src/lib/router.svelte.ts index 55aefe1..ad95b35 100644 --- a/frontend/src/lib/router.svelte.ts +++ b/frontend/src/lib/router.svelte.ts @@ -1,19 +1,21 @@ -let currentPath = $state(getPathWithoutQuery(window.location.hash.slice(1) || '/')) +let currentPath = $state( + getPathWithoutQuery(window.location.hash.slice(1) || "/"), +); function getPathWithoutQuery(hash: string): string { - const queryIndex = hash.indexOf('?') - return queryIndex === -1 ? hash : hash.slice(0, queryIndex) + const queryIndex = hash.indexOf("?"); + return queryIndex === -1 ? hash : hash.slice(0, queryIndex); } -window.addEventListener('hashchange', () => { - currentPath = getPathWithoutQuery(window.location.hash.slice(1) || '/') -}) +window.addEventListener("hashchange", () => { + currentPath = getPathWithoutQuery(window.location.hash.slice(1) || "/"); +}); export function navigate(path: string) { - currentPath = path - window.location.hash = path + currentPath = path; + window.location.hash = path; } export function getCurrentPath() { - return currentPath + return currentPath; } diff --git a/frontend/src/lib/serverConfig.svelte.ts b/frontend/src/lib/serverConfig.svelte.ts index ac6b9f1..640e0c7 100644 --- a/frontend/src/lib/serverConfig.svelte.ts +++ b/frontend/src/lib/serverConfig.svelte.ts @@ -1,13 +1,13 @@ -import { api } from './api' +import { api } from "./api"; interface ServerConfigState { - serverName: string | null - primaryColor: string | null - primaryColorDark: string | null - secondaryColor: string | null - secondaryColorDark: string | null - hasLogo: boolean - loading: boolean + serverName: string | null; + primaryColor: string | null; + primaryColorDark: string | null; + secondaryColor: string | null; + secondaryColorDark: string | null; + hasLogo: boolean; + loading: boolean; } let state = $state({ @@ -18,106 +18,114 @@ let state = $state({ secondaryColorDark: null, hasLogo: false, loading: true, -}) +}); -let initialized = false -let darkModeQuery: MediaQueryList | null = null +let initialized = false; +let darkModeQuery: MediaQueryList | null = null; function isDarkMode(): boolean { - return darkModeQuery?.matches ?? false + return darkModeQuery?.matches ?? false; } function applyColors() { - const root = document.documentElement - const dark = isDarkMode() + const root = document.documentElement; + const dark = isDarkMode(); if (dark) { if (state.primaryColorDark) { - root.style.setProperty('--accent', state.primaryColorDark) + root.style.setProperty("--accent", state.primaryColorDark); } else { - root.style.removeProperty('--accent') + root.style.removeProperty("--accent"); } if (state.secondaryColorDark) { - root.style.setProperty('--secondary', state.secondaryColorDark) + root.style.setProperty("--secondary", state.secondaryColorDark); } else { - root.style.removeProperty('--secondary') + root.style.removeProperty("--secondary"); } } else { if (state.primaryColor) { - root.style.setProperty('--accent', state.primaryColor) + root.style.setProperty("--accent", state.primaryColor); } else { - root.style.removeProperty('--accent') + root.style.removeProperty("--accent"); } if (state.secondaryColor) { - root.style.setProperty('--secondary', state.secondaryColor) + root.style.setProperty("--secondary", state.secondaryColor); } else { - root.style.removeProperty('--secondary') + root.style.removeProperty("--secondary"); } } } function setFavicon(hasLogo: boolean) { - let link = document.querySelector("link[rel~='icon']") + let link = document.querySelector("link[rel~='icon']"); if (hasLogo) { if (!link) { - link = document.createElement('link') - link.rel = 'icon' - document.head.appendChild(link) + link = document.createElement("link"); + link.rel = "icon"; + document.head.appendChild(link); } - link.href = '/logo' + link.href = "/logo"; } else if (link) { - link.remove() + link.remove(); } } export async function initServerConfig(): Promise { - if (initialized) return - initialized = true + if (initialized) return; + initialized = true; - darkModeQuery = window.matchMedia('(prefers-color-scheme: dark)') - darkModeQuery.addEventListener('change', applyColors) + darkModeQuery = window.matchMedia("(prefers-color-scheme: dark)"); + darkModeQuery.addEventListener("change", applyColors); try { - const config = await api.getServerConfig() - state.serverName = config.serverName - state.primaryColor = config.primaryColor - state.primaryColorDark = config.primaryColorDark - state.secondaryColor = config.secondaryColor - state.secondaryColorDark = config.secondaryColorDark - state.hasLogo = !!config.logoCid - document.title = config.serverName - applyColors() - setFavicon(state.hasLogo) + const config = await api.getServerConfig(); + state.serverName = config.serverName; + state.primaryColor = config.primaryColor; + state.primaryColorDark = config.primaryColorDark; + state.secondaryColor = config.secondaryColor; + state.secondaryColorDark = config.secondaryColorDark; + state.hasLogo = !!config.logoCid; + document.title = config.serverName; + applyColors(); + setFavicon(state.hasLogo); } catch { - state.serverName = null + state.serverName = null; } finally { - state.loading = false + state.loading = false; } } export function getServerConfigState() { - return state + return state; } export function setServerName(name: string) { - state.serverName = name - document.title = name + state.serverName = name; + document.title = name; } export function setColors(colors: { - primaryColor?: string | null - primaryColorDark?: string | null - secondaryColor?: string | null - secondaryColorDark?: string | null + primaryColor?: string | null; + primaryColorDark?: string | null; + secondaryColor?: string | null; + secondaryColorDark?: string | null; }) { - if (colors.primaryColor !== undefined) state.primaryColor = colors.primaryColor - if (colors.primaryColorDark !== undefined) state.primaryColorDark = colors.primaryColorDark - if (colors.secondaryColor !== undefined) state.secondaryColor = colors.secondaryColor - if (colors.secondaryColorDark !== undefined) state.secondaryColorDark = colors.secondaryColorDark - applyColors() + if (colors.primaryColor !== undefined) { + state.primaryColor = colors.primaryColor; + } + if (colors.primaryColorDark !== undefined) { + state.primaryColorDark = colors.primaryColorDark; + } + if (colors.secondaryColor !== undefined) { + state.secondaryColor = colors.secondaryColor; + } + if (colors.secondaryColorDark !== undefined) { + state.secondaryColorDark = colors.secondaryColorDark; + } + applyColors(); } export function setHasLogo(hasLogo: boolean) { - state.hasLogo = hasLogo - setFavicon(hasLogo) + state.hasLogo = hasLogo; + setFavicon(hasLogo); } diff --git a/frontend/src/locales/en.json b/frontend/src/locales/en.json index 21f6e90..8bfd8e1 100644 --- a/frontend/src/locales/en.json +++ b/frontend/src/locales/en.json @@ -30,7 +30,17 @@ "lostPasskey": "Lost passkey?", "noAccount": "Don't have an account?", "createAccount": "Create account", - "removeAccount": "Remove from saved accounts" + "removeAccount": "Remove from saved accounts", + "infoSavedAccountsTitle": "Saved accounts", + "infoSavedAccountsDesc": "Click an account to sign in instantly. Your session tokens are stored securely in this browser.", + "infoNewAccountTitle": "New account", + "infoNewAccountDesc": "Use the sign-in button to add a different account. Click the × to remove saved accounts from this browser.", + "infoSecureSignInTitle": "Secure sign-in", + "infoSecureSignInDesc": "You'll be redirected to authenticate securely. If you have passkeys or two-factor authentication enabled, you'll be prompted for those too.", + "infoStaySignedInTitle": "Stay signed in", + "infoStaySignedInDesc": "After signing in, your account will be saved to this browser for quick access next time.", + "infoRecoveryTitle": "Account recovery", + "infoRecoveryDesc": "Lost your password or passkey? Use the recovery links below the sign-in button." }, "verification": { "title": "Verify Your Account", @@ -47,6 +57,17 @@ "register": { "title": "Create Account", "subtitle": "Create a new account on this PDS", + "subtitleKeyChoice": "Choose how to set up your external did:web identity.", + "subtitleInitialDidDoc": "Upload your DID document to continue.", + "subtitleVerify": "Verify your {channel} to continue.", + "subtitleUpdatedDidDoc": "Update your DID document with the PDS signing key.", + "subtitleActivating": "Activating your account...", + "subtitleComplete": "Your account has been created successfully!", + "redirecting": "Redirecting to dashboard...", + "infoIdentityDesc": "Your identity determines how your account is identified across the ATProto network. Most users should choose the standard option.", + "infoContactDesc": "We'll use this to verify your account and send important notifications about your account security.", + "infoNextTitle": "What happens next?", + "infoNextDesc": "After creating your account, you'll verify your contact method and then you're ready to use any ATProto app with your new identity.", "migrateTitle": "Already have a Bluesky account?", "migrateDescription": "You can migrate your existing account to this PDS instead of creating a new one. Your followers, posts, and identity will come with you.", "migrateLink": "Migrate with PDS Moover", @@ -211,12 +232,22 @@ "messages": { "emailCodeSent": "Verification code sent to your notification channel", "emailUpdated": "Email updated successfully", + "emailUpdateFailed": "Failed to update email", "handleUpdated": "Handle updated successfully", + "handleUpdateFailed": "Failed to update handle", "passwordChanged": "Password changed successfully", + "passwordChangeFailed": "Failed to change password", "passwordsMismatch": "Passwords do not match", + "passwordsDoNotMatch": "Passwords do not match", "passwordLength": "Password must be at least 8 characters", + "passwordTooShort": "Password must be at least 8 characters", "deletionCodeSent": "Deletion confirmation sent to your email", + "deletionConfirmationSent": "Deletion confirmation sent to your email", + "deletionRequestFailed": "Failed to request account deletion", + "deleteConfirmation": "Are you absolutely sure you want to delete your account? This cannot be undone.", + "deletionFailed": "Failed to delete account", "repoExported": "Repository exported successfully", + "exportFailed": "Failed to export repository", "confirmDelete": "Are you absolutely sure you want to delete your account? This cannot be undone." } }, @@ -362,6 +393,7 @@ "manageTrustedDevices": "Manage Trusted Devices", "appCompatibility": "App Compatibility", "enterPassword": "Enter your password", + "sessionExpired": "Session expired. Please log in again.", "legacyLoginEnabled": "Legacy app login enabled", "legacyLoginDisabled": "Legacy app login disabled - only OAuth apps can sign in", "failedToUpdatePreference": "Failed to update preference", @@ -421,6 +453,7 @@ "noRecords": "No records in this collection", "recordDetails": "Record Details", "rkey": "Record Key", + "uri": "URI", "cid": "CID", "value": "Value", "deleteRecord": "Delete Record", @@ -463,13 +496,10 @@ "themeColors": "Theme Colors", "themeColorsHint": "Leave blank to use default colors.", "primaryLight": "Primary (Light Mode)", - "primaryLightDefault": "#2c00ff (default)", + "colorDefault": "{color} (default)", "primaryDark": "Primary (Dark Mode)", - "primaryDarkDefault": "#7b6bff (default)", "secondaryLight": "Secondary (Light Mode)", - "secondaryLightDefault": "#ff2400 (default)", "secondaryDark": "Secondary (Dark Mode)", - "secondaryDarkDefault": "#ff6b5b (default)", "configSaved": "Server configuration saved", "saving": "Saving...", "saveConfig": "Save Configuration", @@ -527,7 +557,10 @@ "rememberDevice": "Remember this device", "passkeyHintChecking": "Checking passkey status...", "passkeyHintAvailable": "Sign in with your passkey", - "passkeyHintNotAvailable": "No passkeys registered for this account" + "passkeyHintNotAvailable": "No passkeys registered for this account", + "passkeyHint": "Use your device's biometrics or security key", + "passwordPlaceholder": "Enter your password", + "usePasskey": "Use Passkey" }, "consent": { "title": "Authorize Application", @@ -741,6 +774,7 @@ "didWebBYODHint": "Bring your own domain", "didWebWarningTitle": "Important: Understand the trade-offs", "didWebWarning1": "Permanent tie to this PDS:", + "didWebWarning1Detail": "Your identity will be {did}.", "didWebWarning2": "No recovery mechanism:", "didWebWarning2Detail": "Unlike did:plc, did:web has no rotation keys.", "didWebWarning3": "We commit to you:", @@ -785,6 +819,7 @@ "title": "Trusted Devices", "backToSecurity": "← Security Settings", "description": "Trusted devices can skip two-factor authentication when logging in. Trust is granted for 30 days and automatically extends when you use the device.", + "failedToLoad": "Failed to load trusted devices", "noDevices": "No trusted devices yet.", "noDevicesHint": "When you log in with two-factor authentication enabled, you can choose to trust the device for 30 days.", "lastSeen": "Last seen:", diff --git a/frontend/src/locales/fi.json b/frontend/src/locales/fi.json index 6b09c8c..d744284 100644 --- a/frontend/src/locales/fi.json +++ b/frontend/src/locales/fi.json @@ -30,7 +30,17 @@ "lostPasskey": "Kadotitko pääsyavaimen?", "noAccount": "Eikö sinulla ole tiliä?", "createAccount": "Luo tili", - "removeAccount": "Poista tallennetuista tileistä" + "removeAccount": "Poista tallennetuista tileistä", + "infoSavedAccountsTitle": "Tallennetut tilit", + "infoSavedAccountsDesc": "Napsauta tiliä kirjautuaksesi heti. Istuntotunnuksesi on tallennettu turvallisesti tähän selaimeen.", + "infoNewAccountTitle": "Uusi tili", + "infoNewAccountDesc": "Käytä kirjautumispainiketta lisätäksesi toisen tilin. Napsauta × poistaaksesi tallennettuja tilejä.", + "infoSecureSignInTitle": "Turvallinen kirjautuminen", + "infoSecureSignInDesc": "Sinut ohjataan turvalliseen todennukseen. Jos sinulla on pääsyavaimia tai kaksivaiheinen tunnistautuminen käytössä, sinulta pyydetään myös ne.", + "infoStaySignedInTitle": "Pysy kirjautuneena", + "infoStaySignedInDesc": "Kirjautumisen jälkeen tilisi tallennetaan tähän selaimeen nopeaa pääsyä varten.", + "infoRecoveryTitle": "Tilin palautus", + "infoRecoveryDesc": "Kadotitko salasanasi tai pääsyavaimesi? Käytä palautuslinkkejä kirjautumispainikkeen alla." }, "verification": { "title": "Vahvista tilisi", @@ -47,6 +57,17 @@ "register": { "title": "Luo tili", "subtitle": "Luo uusi tili tälle PDS:lle", + "subtitleKeyChoice": "Valitse, miten haluat määrittää ulkoisen did:web-identiteettisi.", + "subtitleInitialDidDoc": "Lataa DID-dokumenttisi jatkaaksesi.", + "subtitleVerify": "Vahvista {channel} jatkaaksesi.", + "subtitleUpdatedDidDoc": "Päivitä DID-dokumenttisi PDS-allekirjoitusavaimella.", + "subtitleActivating": "Aktivoidaan tiliäsi...", + "subtitleComplete": "Tilisi on luotu onnistuneesti!", + "redirecting": "Siirrytään kojelaudalle...", + "infoIdentityDesc": "Identiteettisi määrittää, miten tilisi tunnistetaan ATProto-verkossa. Useimpien käyttäjien tulisi valita vakiovaihtoehto.", + "infoContactDesc": "Käytämme tätä tilisi vahvistamiseen ja tärkeiden turvallisuusilmoitusten lähettämiseen.", + "infoNextTitle": "Mitä tapahtuu seuraavaksi?", + "infoNextDesc": "Tilin luomisen jälkeen vahvistat yhteysmenetelmäsi ja olet valmis käyttämään mitä tahansa ATProto-sovellusta uudella identiteetilläsi.", "migrateTitle": "Onko sinulla jo Bluesky-tili?", "migrateDescription": "Voit siirtää olemassa olevan tilisi tälle PDS:lle uuden luomisen sijaan. Seuraajasi, julkaisusi ja identiteettisi siirtyvät mukana.", "migrateLink": "Siirrä PDS Mooverilla", @@ -211,12 +232,22 @@ "messages": { "emailCodeSent": "Vahvistuskoodi lähetetty ilmoituskanavallesi", "emailUpdated": "Sähköposti päivitetty", + "emailUpdateFailed": "Sähköpostin päivitys epäonnistui", "handleUpdated": "Käyttäjänimi päivitetty", + "handleUpdateFailed": "Käyttäjänimen päivitys epäonnistui", "passwordChanged": "Salasana vaihdettu", + "passwordChangeFailed": "Salasanan vaihto epäonnistui", "passwordsMismatch": "Salasanat eivät täsmää", + "passwordsDoNotMatch": "Salasanat eivät täsmää", "passwordLength": "Salasanan on oltava vähintään 8 merkkiä", + "passwordTooShort": "Salasanan on oltava vähintään 8 merkkiä", "deletionCodeSent": "Poistovahvistus lähetetty sähköpostiisi", + "deletionConfirmationSent": "Poistovahvistus lähetetty sähköpostiisi", + "deletionRequestFailed": "Tilin poistopyyntö epäonnistui", + "deleteConfirmation": "Oletko täysin varma, että haluat poistaa tilisi? Tätä ei voi perua.", + "deletionFailed": "Tilin poisto epäonnistui", "repoExported": "Tietovarasto viety", + "exportFailed": "Tietovaraston vienti epäonnistui", "confirmDelete": "Oletko täysin varma, että haluat poistaa tilisi? Tätä ei voi perua." } }, @@ -362,6 +393,7 @@ "manageTrustedDevices": "Hallitse luotettuja laitteita", "appCompatibility": "Sovellusyhteensopivuus", "enterPassword": "Syötä salasanasi", + "sessionExpired": "Istunto vanhentunut. Kirjaudu sisään uudelleen.", "legacyLoginEnabled": "Vanhentuneiden sovellusten kirjautuminen käytössä", "legacyLoginDisabled": "Vanhentuneiden sovellusten kirjautuminen poistettu käytöstä - vain OAuth-sovellukset voivat kirjautua", "failedToUpdatePreference": "Asetuksen päivittäminen epäonnistui", @@ -421,6 +453,7 @@ "noRecords": "Ei tietueita tässä kokoelmassa", "recordDetails": "Tietueen tiedot", "rkey": "Tietueavain", + "uri": "URI", "cid": "CID", "value": "Arvo", "deleteRecord": "Poista tietue", @@ -464,9 +497,6 @@ "themeColorsHint": "Jätä tyhjäksi käyttääksesi oletusvärejä.", "primaryLight": "Ensisijainen (vaalea tila)", "primaryDark": "Ensisijainen (tumma tila)", - "accentLight": "Korostus (vaalea tila)", - "accentDark": "Korostus (tumma tila)", - "faviconExample": "Favicon-esimerkki", "configSaved": "Palvelinasetukset tallennettu", "saving": "Tallennetaan...", "saveConfig": "Tallenna asetukset", @@ -508,7 +538,10 @@ "deleteConfirm": "Poista tili @{handle}? Tätä ei voi perua.", "verified": "Vahvistettu", "unverified": "Vahvistamaton", - "deactivated": "Poistettu käytöstä" + "deactivated": "Poistettu käytöstä", + "colorDefault": "{color} (oletus)", + "secondaryLight": "Toissijainen (vaalea tila)", + "secondaryDark": "Toissijainen (tumma tila)" }, "oauth": { "login": { @@ -524,7 +557,10 @@ "rememberDevice": "Muista tämä laite", "passkeyHintChecking": "Tarkistetaan pääsyavaimen tilaa...", "passkeyHintAvailable": "Kirjaudu pääsyavaimellasi", - "passkeyHintNotAvailable": "Ei rekisteröityjä pääsyavaimia tälle tilille" + "passkeyHintNotAvailable": "Ei rekisteröityjä pääsyavaimia tälle tilille", + "passkeyHint": "Käytä laitteesi biometriikkaa tai suojausavainta", + "passwordPlaceholder": "Syötä salasanasi", + "usePasskey": "Käytä pääsyavainta" }, "consent": { "title": "Valtuuta sovellus", @@ -740,13 +776,66 @@ "handleNoDots": "Käyttäjänimi ei voi sisältää pisteitä. Voit määrittää oman verkkotunnuksen tilin luomisen jälkeen.", "passkeysNotSupported": "Pääsyavaimia ei tueta tässä selaimessa. Luo salasanapohjainen tili tai käytä selainta, joka tukee pääsyavaimia.", "passkeyCancelled": "Pääsyavaimen luominen peruutettu", - "passkeyFailed": "Pääsyavaimen rekisteröinti epäonnistui" - } + "passkeyFailed": "Pääsyavaimen rekisteröinti epäonnistui", + "signalRequired": "Puhelinnumero vaaditaan Signal-vahvistukseen", + "inviteRequired": "Kutsukoodi vaaditaan", + "externalDidRequired": "Ulkoinen did:web vaaditaan", + "emailRequired": "Sähköposti vaaditaan sähköpostivahvistukseen", + "telegramRequired": "Telegram-käyttäjänimi vaaditaan Telegram-vahvistukseen", + "externalDidFormat": "Ulkoisen DID:n on alettava did:web:", + "discordRequired": "Discord-tunnus vaaditaan Discord-vahvistukseen" + }, + "whyPasskeyBullet1": "Ei voi kalastella tai varastaa tietomurroissa", + "whyPasskeyBullet2": "Käyttää laitteistopohjaisia salausavaimia", + "whyPasskeyBullet3": "Vaatii biometrisen tunnistuksen tai laitteen PIN-koodin", + "whyPasskeyOnly": "Miksi vain pääsyavain?", + "whyPasskeyOnlyDesc": "Pääsyavaintilit ovat turvallisempia kuin salasanapohjaiset tilit, koska ne:", + "subtitleInitialDidDoc": "Lataa DID-dokumenttisi jatkaaksesi.", + "subtitleUpdatedDidDoc": "Päivitä DID-dokumenttisi PDS-allekirjoitusavaimella.", + "subtitleActivating": "Aktivoidaan tiliäsi...", + "subtitleComplete": "Tilisi on luotu onnistuneesti!", + "subtitleCreating": "Luodaan tiliäsi...", + "subtitleAppPassword": "Tallenna sovellussalasanasi kolmannen osapuolen sovelluksia varten.", + "creatingPasskey": "Luodaan pääsyavainta...", + "passkeyPrompt": "Napsauta alla olevaa painiketta luodaksesi pääsyavaimesi. Sinua pyydetään käyttämään:", + "passkeyPromptBullet1": "Touch ID tai Face ID", + "passkeyPromptBullet2": "Laitteesi PIN-koodi tai salasana", + "passkeyPromptBullet3": "Turva-avain (jos sinulla on sellainen)", + "identityType": "Identiteettityyppi", + "identityTypeHint": "Valitse, miten hajautettua identiteettiäsi hallitaan.", + "passkeyNameLabel": "Pääsyavaimen nimi (valinnainen)", + "passkeyNamePlaceholder": "esim. MacBook Touch ID", + "passkeyNameHint": "Ystävällinen nimi tämän pääsyavaimen tunnistamiseksi", + "createPasskey": "Luo pääsyavain", + "didPlcRecommended": "did:plc (Suositeltava)", + "didPlcHint": "Siirrettävä identiteetti, jota hallinnoi PLC Directory", + "didWeb": "did:web", + "didWebHint": "Tällä PDS:llä isännöity identiteetti (lue varoitus alla)", + "didWebBYOD": "did:web (BYOD)", + "didWebBYODHint": "Tuo oma verkkotunnuksesi", + "didWebWarningTitle": "Tärkeää: Ymmärrä kompromissit", + "didWebWarning1": "Pysyvä sidos tähän PDS:ään:", + "didWebWarning1Detail": "Identiteettisi {did} on sidottu tähän palvelimeen.", + "didWebWarning2": "Ei palautusmekanismia:", + "didWebWarning2Detail": "Toisin kuin did:plc, did:web ei sisällä kiertoavaimia.", + "didWebWarning3": "Sitoudumme sinulle:", + "didWebWarning3Detail": "Jos siirryt pois, jatkamme minimaalisen DID-dokumentin tarjoamista.", + "didWebWarning4": "Suositus:", + "didWebWarning4Detail": "Valitse did:plc, ellei sinulla ole erityistä syytä suosia did:web.", + "externalDidHint": "Sinun on tarjottava DID-dokumentti osoitteessa", + "continue": "Jatka", + "back": "Takaisin", + "loading": "Ladataan...", + "redirecting": "Ohjataan hallintapaneeliin...", + "handleDotWarning": "Mukautetut verkkotunnuskahvat voidaan määrittää tilin luomisen jälkeen.", + "wantTraditional": "Haluatko perinteisen salasanan?", + "registerWithPassword": "Rekisteröidy salasanalla" }, "trustedDevices": { "title": "Luotetut laitteet", "backToSecurity": "← Turvallisuusasetukset", "description": "Luotetut laitteet voivat ohittaa kaksivaiheisen tunnistautumisen kirjautuessaan. Luottamus myönnetään 30 päiväksi ja jatkuu automaattisesti, kun käytät laitetta.", + "failedToLoad": "Luotettujen laitteiden lataaminen epäonnistui", "noDevices": "Ei vielä luotettuja laitteita.", "noDevicesHint": "Kun kirjaudut sisään kaksivaiheisen tunnistautumisen ollessa käytössä, voit valita luottaa laitteeseen 30 päivää.", "lastSeen": "Viimeksi nähty:", diff --git a/frontend/src/locales/ja.json b/frontend/src/locales/ja.json index c09a408..57820a0 100644 --- a/frontend/src/locales/ja.json +++ b/frontend/src/locales/ja.json @@ -30,7 +30,17 @@ "lostPasskey": "パスキーを紛失しましたか?", "noAccount": "アカウントをお持ちでないですか?", "createAccount": "アカウントを作成", - "removeAccount": "保存済みアカウントから削除" + "removeAccount": "保存済みアカウントから削除", + "infoSavedAccountsTitle": "保存済みアカウント", + "infoSavedAccountsDesc": "アカウントをクリックすると即座にサインインできます。セッショントークンはこのブラウザに安全に保存されています。", + "infoNewAccountTitle": "新規アカウント", + "infoNewAccountDesc": "サインインボタンで別のアカウントを追加できます。×をクリックすると保存済みアカウントを削除できます。", + "infoSecureSignInTitle": "安全なサインイン", + "infoSecureSignInDesc": "安全な認証のためにリダイレクトされます。パスキーや二要素認証が有効な場合は、それらも求められます。", + "infoStaySignedInTitle": "サインイン状態を維持", + "infoStaySignedInDesc": "サインイン後、アカウントはこのブラウザに保存され、次回から素早くアクセスできます。", + "infoRecoveryTitle": "アカウント復旧", + "infoRecoveryDesc": "パスワードやパスキーを紛失しましたか?サインインボタンの下の復旧リンクをご利用ください。" }, "verification": { "title": "アカウント確認", @@ -47,6 +57,17 @@ "register": { "title": "アカウント作成", "subtitle": "この PDS で新規アカウントを作成", + "subtitleKeyChoice": "外部 did:web アイデンティティの設定方法を選択してください。", + "subtitleInitialDidDoc": "続行するには DID ドキュメントをアップロードしてください。", + "subtitleVerify": "続行するには{channel}を確認してください。", + "subtitleUpdatedDidDoc": "PDS 署名キーで DID ドキュメントを更新してください。", + "subtitleActivating": "アカウントを有効化しています...", + "subtitleComplete": "アカウントが正常に作成されました!", + "redirecting": "ダッシュボードへ移動中...", + "infoIdentityDesc": "アイデンティティは、ATProto ネットワーク上でアカウントがどのように識別されるかを決定します。ほとんどのユーザーは標準オプションを選択してください。", + "infoContactDesc": "この情報はアカウントの確認と、アカウントセキュリティに関する重要な通知の送信に使用されます。", + "infoNextTitle": "次のステップは?", + "infoNextDesc": "アカウント作成後、連絡方法を確認すると、新しいアイデンティティで任意の ATProto アプリを使用できます。", "migrateTitle": "すでにBlueskyアカウントをお持ちですか?", "migrateDescription": "新しいアカウントを作成する代わりに、既存のアカウントをこのPDSに移行できます。フォロワー、投稿、IDも一緒に移行されます。", "migrateLink": "PDS Mooverで移行する", @@ -211,12 +232,22 @@ "messages": { "emailCodeSent": "通知チャンネルに確認コードを送信しました", "emailUpdated": "メールを更新しました", + "emailUpdateFailed": "メールの更新に失敗しました", "handleUpdated": "ハンドルを更新しました", + "handleUpdateFailed": "ハンドルの更新に失敗しました", "passwordChanged": "パスワードを変更しました", + "passwordChangeFailed": "パスワードの変更に失敗しました", "passwordsMismatch": "パスワードが一致しません", + "passwordsDoNotMatch": "パスワードが一致しません", "passwordLength": "パスワードは8文字以上である必要があります", + "passwordTooShort": "パスワードは8文字以上である必要があります", "deletionCodeSent": "削除確認をメールに送信しました", + "deletionConfirmationSent": "削除確認をメールに送信しました", + "deletionRequestFailed": "アカウント削除リクエストに失敗しました", + "deleteConfirmation": "本当にアカウントを削除しますか?この操作は取り消せません。", + "deletionFailed": "アカウントの削除に失敗しました", "repoExported": "リポジトリをエクスポートしました", + "exportFailed": "リポジトリのエクスポートに失敗しました", "confirmDelete": "本当にアカウントを削除しますか?この操作は取り消せません。" } }, @@ -362,6 +393,7 @@ "manageTrustedDevices": "信頼済みデバイスを管理", "appCompatibility": "アプリ互換性", "enterPassword": "パスワードを入力", + "sessionExpired": "セッションが期限切れです。再度ログインしてください。", "legacyLoginEnabled": "レガシーアプリログインが有効", "legacyLoginDisabled": "レガシーアプリログインが無効 - OAuth アプリのみサインイン可能", "failedToUpdatePreference": "設定の更新に失敗しました", @@ -421,6 +453,7 @@ "noRecords": "このコレクションにレコードはありません", "recordDetails": "レコード詳細", "rkey": "レコードキー", + "uri": "URI", "cid": "CID", "value": "値", "deleteRecord": "レコードを削除", @@ -464,9 +497,6 @@ "themeColorsHint": "デフォルトカラーを使用する場合は空白のままにしてください。", "primaryLight": "プライマリ(ライトモード)", "primaryDark": "プライマリ(ダークモード)", - "accentLight": "アクセント(ライトモード)", - "accentDark": "アクセント(ダークモード)", - "faviconExample": "ファビコン例", "configSaved": "サーバー設定を保存しました", "saving": "保存中...", "saveConfig": "設定を保存", @@ -508,7 +538,10 @@ "deleteConfirm": "アカウント @{handle} を削除しますか?この操作は取り消せません。", "verified": "確認済み", "unverified": "未確認", - "deactivated": "無効化" + "deactivated": "無効化", + "colorDefault": "{color}(デフォルト)", + "secondaryLight": "セカンダリ(ライトモード)", + "secondaryDark": "セカンダリ(ダークモード)" }, "oauth": { "login": { @@ -524,7 +557,10 @@ "rememberDevice": "このデバイスを記憶する", "passkeyHintChecking": "パスキーの状態を確認中...", "passkeyHintAvailable": "パスキーでサインイン", - "passkeyHintNotAvailable": "このアカウントにはパスキーが登録されていません" + "passkeyHintNotAvailable": "このアカウントにはパスキーが登録されていません", + "passkeyHint": "デバイスの生体認証またはセキュリティキーを使用", + "passwordPlaceholder": "パスワードを入力", + "usePasskey": "パスキーを使用" }, "consent": { "title": "アプリを承認", @@ -740,13 +776,66 @@ "handleNoDots": "ハンドルにドットは使用できません。アカウント作成後にカスタムドメインを設定できます。", "passkeysNotSupported": "このブラウザではパスキーがサポートされていません。パスワードベースのアカウントを作成するか、パスキーをサポートするブラウザを使用してください。", "passkeyCancelled": "パスキーの作成がキャンセルされました", - "passkeyFailed": "パスキーの登録に失敗しました" - } + "passkeyFailed": "パスキーの登録に失敗しました", + "signalRequired": "Signal認証には電話番号が必要です", + "inviteRequired": "招待コードが必要です", + "externalDidRequired": "外部did:webが必要です", + "emailRequired": "メール認証にはメールアドレスが必要です", + "telegramRequired": "Telegram認証にはTelegramユーザー名が必要です", + "externalDidFormat": "外部DIDはdid:web:で始まる必要があります", + "discordRequired": "Discord認証にはDiscord IDが必要です" + }, + "whyPasskeyBullet1": "フィッシングやデータ侵害で盗まれない", + "whyPasskeyBullet2": "ハードウェア支援の暗号鍵を使用", + "whyPasskeyBullet3": "生体認証またはデバイスPINが必要", + "whyPasskeyOnly": "なぜパスキーのみ?", + "whyPasskeyOnlyDesc": "パスキーアカウントはパスワードベースのアカウントより安全です:", + "subtitleInitialDidDoc": "続行するにはDIDドキュメントをアップロードしてください。", + "subtitleUpdatedDidDoc": "PDS署名鍵でDIDドキュメントを更新してください。", + "subtitleActivating": "アカウントを有効化しています...", + "subtitleComplete": "アカウントが正常に作成されました!", + "subtitleCreating": "アカウントを作成しています...", + "subtitleAppPassword": "サードパーティアプリ用のアプリパスワードを保存してください。", + "creatingPasskey": "パスキーを作成中...", + "passkeyPrompt": "下のボタンをクリックしてパスキーを作成してください。以下の使用を求められます:", + "passkeyPromptBullet1": "Touch IDまたはFace ID", + "passkeyPromptBullet2": "デバイスのPINまたはパスワード", + "passkeyPromptBullet3": "セキュリティキー(お持ちの場合)", + "identityType": "アイデンティティタイプ", + "identityTypeHint": "分散型アイデンティティの管理方法を選択してください。", + "passkeyNameLabel": "パスキー名(任意)", + "passkeyNamePlaceholder": "例:MacBook Touch ID", + "passkeyNameHint": "このパスキーを識別するための名前", + "createPasskey": "パスキーを作成", + "didPlcRecommended": "did:plc(推奨)", + "didPlcHint": "PLC Directoryで管理されるポータブルなアイデンティティ", + "didWeb": "did:web", + "didWebHint": "このPDSでホストされるアイデンティティ(以下の警告を参照)", + "didWebBYOD": "did:web(BYOD)", + "didWebBYODHint": "独自ドメインを持ち込む", + "didWebWarningTitle": "重要:トレードオフを理解する", + "didWebWarning1": "このPDSへの永続的な紐付け:", + "didWebWarning1Detail": "あなたのアイデンティティ{did}はこのサーバーに紐付けられます。", + "didWebWarning2": "回復メカニズムなし:", + "didWebWarning2Detail": "did:plcと異なり、did:webにはローテーションキーがありません。", + "didWebWarning3": "私たちの約束:", + "didWebWarning3Detail": "移行後も最小限のDIDドキュメントを提供し続けます。", + "didWebWarning4": "推奨事項:", + "didWebWarning4Detail": "did:webを好む特別な理由がない限り、did:plcを選択してください。", + "externalDidHint": "以下の場所でDIDドキュメントを提供する必要があります", + "continue": "続行", + "back": "戻る", + "loading": "読み込み中...", + "redirecting": "ダッシュボードに移動中...", + "handleDotWarning": "カスタムドメインハンドルはアカウント作成後に設定できます。", + "wantTraditional": "従来のパスワードを使用しますか?", + "registerWithPassword": "パスワードで登録" }, "trustedDevices": { "title": "信頼済みデバイス", "backToSecurity": "← セキュリティ設定", "description": "信頼済みデバイスはログイン時に二要素認証をスキップできます。信頼は30日間有効で、デバイスを使用すると自動的に延長されます。", + "failedToLoad": "信頼済みデバイスの読み込みに失敗しました", "noDevices": "信頼済みデバイスはまだありません。", "noDevicesHint": "二要素認証を有効にしてログインする際に、デバイスを30日間信頼することを選択できます。", "lastSeen": "最終使用:", diff --git a/frontend/src/locales/ko.json b/frontend/src/locales/ko.json index a47d35c..953a76a 100644 --- a/frontend/src/locales/ko.json +++ b/frontend/src/locales/ko.json @@ -30,7 +30,17 @@ "lostPasskey": "패스키를 분실하셨나요?", "noAccount": "계정이 없으신가요?", "createAccount": "계정 만들기", - "removeAccount": "저장된 계정에서 삭제" + "removeAccount": "저장된 계정에서 삭제", + "infoSavedAccountsTitle": "저장된 계정", + "infoSavedAccountsDesc": "계정을 클릭하면 즉시 로그인할 수 있습니다. 세션 토큰은 이 브라우저에 안전하게 저장됩니다.", + "infoNewAccountTitle": "새 계정", + "infoNewAccountDesc": "로그인 버튼을 사용하여 다른 계정을 추가하세요. ×를 클릭하여 저장된 계정을 제거할 수 있습니다.", + "infoSecureSignInTitle": "안전한 로그인", + "infoSecureSignInDesc": "안전한 인증을 위해 리디렉션됩니다. 패스키나 2단계 인증이 활성화되어 있으면 해당 인증도 요청됩니다.", + "infoStaySignedInTitle": "로그인 유지", + "infoStaySignedInDesc": "로그인 후 계정이 이 브라우저에 저장되어 다음에 빠르게 접속할 수 있습니다.", + "infoRecoveryTitle": "계정 복구", + "infoRecoveryDesc": "비밀번호나 패스키를 분실하셨나요? 로그인 버튼 아래의 복구 링크를 사용하세요." }, "verification": { "title": "계정 인증", @@ -47,6 +57,17 @@ "register": { "title": "계정 만들기", "subtitle": "이 PDS에 새 계정을 만듭니다", + "subtitleKeyChoice": "외부 did:web 신원을 설정하는 방법을 선택하세요.", + "subtitleInitialDidDoc": "계속하려면 DID 문서를 업로드하세요.", + "subtitleVerify": "계속하려면 {channel}을(를) 인증하세요.", + "subtitleUpdatedDidDoc": "PDS 서명 키로 DID 문서를 업데이트하세요.", + "subtitleActivating": "계정을 활성화하는 중...", + "subtitleComplete": "계정이 성공적으로 생성되었습니다!", + "redirecting": "대시보드로 이동 중...", + "infoIdentityDesc": "신원은 ATProto 네트워크에서 계정이 어떻게 식별되는지를 결정합니다. 대부분의 사용자는 표준 옵션을 선택해야 합니다.", + "infoContactDesc": "이 정보는 계정 인증과 계정 보안에 관한 중요한 알림을 보내는 데 사용됩니다.", + "infoNextTitle": "다음 단계는?", + "infoNextDesc": "계정 생성 후 연락 방법을 인증하면 새로운 신원으로 모든 ATProto 앱을 사용할 수 있습니다.", "migrateTitle": "이미 Bluesky 계정이 있으신가요?", "migrateDescription": "새 계정을 만드는 대신 기존 계정을 이 PDS로 마이그레이션할 수 있습니다. 팔로워, 게시물, ID가 함께 이전됩니다.", "migrateLink": "PDS Moover로 마이그레이션", @@ -211,12 +232,22 @@ "messages": { "emailCodeSent": "알림 채널로 인증 코드를 보냈습니다", "emailUpdated": "이메일이 업데이트되었습니다", + "emailUpdateFailed": "이메일 업데이트에 실패했습니다", "handleUpdated": "핸들이 업데이트되었습니다", + "handleUpdateFailed": "핸들 업데이트에 실패했습니다", "passwordChanged": "비밀번호가 변경되었습니다", + "passwordChangeFailed": "비밀번호 변경에 실패했습니다", "passwordsMismatch": "비밀번호가 일치하지 않습니다", + "passwordsDoNotMatch": "비밀번호가 일치하지 않습니다", "passwordLength": "비밀번호는 8자 이상이어야 합니다", + "passwordTooShort": "비밀번호는 8자 이상이어야 합니다", "deletionCodeSent": "이메일로 삭제 확인을 보냈습니다", + "deletionConfirmationSent": "이메일로 삭제 확인을 보냈습니다", + "deletionRequestFailed": "계정 삭제 요청에 실패했습니다", + "deleteConfirmation": "정말로 계정을 삭제하시겠습니까? 이 작업은 되돌릴 수 없습니다.", + "deletionFailed": "계정 삭제에 실패했습니다", "repoExported": "저장소를 내보냈습니다", + "exportFailed": "저장소 내보내기에 실패했습니다", "confirmDelete": "정말로 계정을 삭제하시겠습니까? 이 작업은 되돌릴 수 없습니다." } }, @@ -362,6 +393,7 @@ "manageTrustedDevices": "신뢰할 수 있는 기기 관리", "appCompatibility": "앱 호환성", "enterPassword": "비밀번호를 입력하세요", + "sessionExpired": "세션이 만료되었습니다. 다시 로그인하세요.", "legacyLoginEnabled": "레거시 앱 로그인 활성화됨", "legacyLoginDisabled": "레거시 앱 로그인 비활성화됨 - OAuth 앱만 로그인 가능", "failedToUpdatePreference": "설정 업데이트에 실패했습니다", @@ -421,6 +453,7 @@ "noRecords": "이 컬렉션에 레코드가 없습니다", "recordDetails": "레코드 세부 정보", "rkey": "레코드 키", + "uri": "URI", "cid": "CID", "value": "값", "deleteRecord": "레코드 삭제", @@ -464,9 +497,6 @@ "themeColorsHint": "기본 색상을 사용하려면 비워 두세요.", "primaryLight": "기본 (라이트 모드)", "primaryDark": "기본 (다크 모드)", - "accentLight": "강조 (라이트 모드)", - "accentDark": "강조 (다크 모드)", - "faviconExample": "파비콘 예시", "configSaved": "서버 설정이 저장되었습니다", "saving": "저장 중...", "saveConfig": "설정 저장", @@ -508,7 +538,10 @@ "deleteConfirm": "계정 @{handle}을(를) 삭제하시겠습니까? 이 작업은 되돌릴 수 없습니다.", "verified": "인증됨", "unverified": "미인증", - "deactivated": "비활성화됨" + "deactivated": "비활성화됨", + "colorDefault": "{color} (기본값)", + "secondaryLight": "보조 (라이트 모드)", + "secondaryDark": "보조 (다크 모드)" }, "oauth": { "login": { @@ -524,7 +557,10 @@ "rememberDevice": "이 기기 기억하기", "passkeyHintChecking": "패스키 상태 확인 중...", "passkeyHintAvailable": "패스키로 로그인", - "passkeyHintNotAvailable": "이 계정에 등록된 패스키가 없습니다" + "passkeyHintNotAvailable": "이 계정에 등록된 패스키가 없습니다", + "passkeyHint": "기기의 생체 인식 또는 보안 키 사용", + "passwordPlaceholder": "비밀번호 입력", + "usePasskey": "패스키 사용" }, "consent": { "title": "앱 승인", @@ -740,13 +776,66 @@ "handleNoDots": "핸들에 점을 포함할 수 없습니다. 계정 생성 후 사용자 정의 도메인을 설정할 수 있습니다.", "passkeysNotSupported": "이 브라우저에서 패스키가 지원되지 않습니다. 비밀번호 기반 계정을 만들거나 패스키를 지원하는 브라우저를 사용하세요.", "passkeyCancelled": "패스키 생성이 취소되었습니다", - "passkeyFailed": "패스키 등록에 실패했습니다" - } + "passkeyFailed": "패스키 등록에 실패했습니다", + "signalRequired": "Signal 인증에는 전화번호가 필요합니다", + "inviteRequired": "초대 코드가 필요합니다", + "externalDidRequired": "외부 did:web이 필요합니다", + "emailRequired": "이메일 인증에는 이메일이 필요합니다", + "telegramRequired": "Telegram 인증에는 Telegram 사용자 이름이 필요합니다", + "externalDidFormat": "외부 DID는 did:web:으로 시작해야 합니다", + "discordRequired": "Discord 인증에는 Discord ID가 필요합니다" + }, + "whyPasskeyBullet1": "피싱이나 데이터 유출로 도난당할 수 없음", + "whyPasskeyBullet2": "하드웨어 기반 암호화 키 사용", + "whyPasskeyBullet3": "생체 인식 또는 기기 PIN 필요", + "whyPasskeyOnly": "왜 패스키만 사용하나요?", + "whyPasskeyOnlyDesc": "패스키 계정은 비밀번호 기반 계정보다 안전합니다:", + "subtitleInitialDidDoc": "계속하려면 DID 문서를 업로드하세요.", + "subtitleUpdatedDidDoc": "PDS 서명 키로 DID 문서를 업데이트하세요.", + "subtitleActivating": "계정을 활성화하는 중...", + "subtitleComplete": "계정이 성공적으로 생성되었습니다!", + "subtitleCreating": "계정을 생성하는 중...", + "subtitleAppPassword": "서드파티 앱용 앱 비밀번호를 저장하세요.", + "creatingPasskey": "패스키 생성 중...", + "passkeyPrompt": "아래 버튼을 클릭하여 패스키를 생성하세요. 다음을 사용하라는 메시지가 표시됩니다:", + "passkeyPromptBullet1": "Touch ID 또는 Face ID", + "passkeyPromptBullet2": "기기 PIN 또는 비밀번호", + "passkeyPromptBullet3": "보안 키 (있는 경우)", + "identityType": "아이덴티티 유형", + "identityTypeHint": "분산 아이덴티티 관리 방법을 선택하세요.", + "passkeyNameLabel": "패스키 이름 (선택사항)", + "passkeyNamePlaceholder": "예: MacBook Touch ID", + "passkeyNameHint": "이 패스키를 식별할 수 있는 이름", + "createPasskey": "패스키 생성", + "didPlcRecommended": "did:plc (권장)", + "didPlcHint": "PLC Directory에서 관리하는 이동 가능한 아이덴티티", + "didWeb": "did:web", + "didWebHint": "이 PDS에서 호스팅되는 아이덴티티 (아래 경고 읽기)", + "didWebBYOD": "did:web (BYOD)", + "didWebBYODHint": "자체 도메인 사용", + "didWebWarningTitle": "중요: 장단점 이해하기", + "didWebWarning1": "이 PDS에 영구적으로 연결됨:", + "didWebWarning1Detail": "귀하의 아이덴티티 {did}는 이 서버에 연결됩니다.", + "didWebWarning2": "복구 메커니즘 없음:", + "didWebWarning2Detail": "did:plc와 달리 did:web에는 순환 키가 없습니다.", + "didWebWarning3": "우리의 약속:", + "didWebWarning3Detail": "마이그레이션하더라도 최소한의 DID 문서를 계속 제공합니다.", + "didWebWarning4": "권장 사항:", + "didWebWarning4Detail": "did:web을 선호할 특별한 이유가 없다면 did:plc를 선택하세요.", + "externalDidHint": "다음 위치에서 DID 문서를 제공해야 합니다", + "continue": "계속", + "back": "뒤로", + "loading": "로딩 중...", + "redirecting": "대시보드로 이동 중...", + "handleDotWarning": "사용자 정의 도메인 핸들은 계정 생성 후 설정할 수 있습니다.", + "wantTraditional": "기존 비밀번호를 원하시나요?", + "registerWithPassword": "비밀번호로 가입" }, "trustedDevices": { "title": "신뢰할 수 있는 기기", "backToSecurity": "← 보안 설정", "description": "신뢰할 수 있는 기기는 로그인 시 2단계 인증을 건너뛸 수 있습니다. 신뢰는 30일간 유효하며 기기를 사용할 때 자동으로 연장됩니다.", + "failedToLoad": "신뢰할 수 있는 기기를 불러오지 못했습니다", "noDevices": "신뢰할 수 있는 기기가 아직 없습니다.", "noDevicesHint": "2단계 인증이 활성화된 상태로 로그인할 때 기기를 30일간 신뢰하도록 선택할 수 있습니다.", "lastSeen": "마지막 접속:", diff --git a/frontend/src/locales/sv.json b/frontend/src/locales/sv.json index 4001795..1171603 100644 --- a/frontend/src/locales/sv.json +++ b/frontend/src/locales/sv.json @@ -30,7 +30,17 @@ "lostPasskey": "Tappat bort nyckeln?", "noAccount": "Har du inget konto?", "createAccount": "Skapa konto", - "removeAccount": "Ta bort från sparade konton" + "removeAccount": "Ta bort från sparade konton", + "infoSavedAccountsTitle": "Sparade konton", + "infoSavedAccountsDesc": "Klicka på ett konto för att logga in direkt. Dina sessionstoken lagras säkert i denna webbläsare.", + "infoNewAccountTitle": "Nytt konto", + "infoNewAccountDesc": "Använd inloggningsknappen för att lägga till ett annat konto. Klicka på × för att ta bort sparade konton.", + "infoSecureSignInTitle": "Säker inloggning", + "infoSecureSignInDesc": "Du omdirigeras för säker autentisering. Om du har aktiverat nycklar eller tvåfaktorsautentisering kommer du också att behöva ange dessa.", + "infoStaySignedInTitle": "Förbli inloggad", + "infoStaySignedInDesc": "Efter inloggning sparas ditt konto i denna webbläsare för snabb åtkomst nästa gång.", + "infoRecoveryTitle": "Kontoåterställning", + "infoRecoveryDesc": "Har du tappat bort ditt lösenord eller din nyckel? Använd återställningslänkarna under inloggningsknappen." }, "verification": { "title": "Verifiera ditt konto", @@ -47,6 +57,17 @@ "register": { "title": "Skapa konto", "subtitle": "Skapa ett nytt konto på denna PDS", + "subtitleKeyChoice": "Välj hur du vill konfigurera din externa did:web-identitet.", + "subtitleInitialDidDoc": "Ladda upp ditt DID-dokument för att fortsätta.", + "subtitleVerify": "Verifiera din {channel} för att fortsätta.", + "subtitleUpdatedDidDoc": "Uppdatera ditt DID-dokument med PDS-signeringsnyckeln.", + "subtitleActivating": "Aktiverar ditt konto...", + "subtitleComplete": "Ditt konto har skapats!", + "redirecting": "Omdirigerar till kontrollpanelen...", + "infoIdentityDesc": "Din identitet avgör hur ditt konto identifieras i ATProto-nätverket. De flesta användare bör välja standardalternativet.", + "infoContactDesc": "Vi använder detta för att verifiera ditt konto och skicka viktiga meddelanden om din kontosäkerhet.", + "infoNextTitle": "Vad händer härnäst?", + "infoNextDesc": "Efter att du skapat ditt konto verifierar du din kontaktmetod och sedan är du redo att använda vilken ATProto-app som helst med din nya identitet.", "migrateTitle": "Har du redan ett Bluesky-konto?", "migrateDescription": "Du kan flytta ditt befintliga konto till denna PDS istället för att skapa ett nytt. Dina följare, inlägg och identitet följer med.", "migrateLink": "Flytta med PDS Moover", @@ -211,12 +232,22 @@ "messages": { "emailCodeSent": "Verifieringskod skickad till din meddelandekanal", "emailUpdated": "E-post uppdaterad", + "emailUpdateFailed": "Kunde inte uppdatera e-post", "handleUpdated": "Användarnamn uppdaterat", + "handleUpdateFailed": "Kunde inte uppdatera användarnamn", "passwordChanged": "Lösenord ändrat", + "passwordChangeFailed": "Kunde inte ändra lösenord", "passwordsMismatch": "Lösenorden matchar inte", + "passwordsDoNotMatch": "Lösenorden matchar inte", "passwordLength": "Lösenordet måste vara minst 8 tecken", + "passwordTooShort": "Lösenordet måste vara minst 8 tecken", "deletionCodeSent": "Bekräftelse för radering skickad till din e-post", + "deletionConfirmationSent": "Bekräftelse för radering skickad till din e-post", + "deletionRequestFailed": "Kunde inte begära kontoradering", + "deleteConfirmation": "Är du helt säker på att du vill radera ditt konto? Detta kan inte ångras.", + "deletionFailed": "Kunde inte radera kontot", "repoExported": "Arkiv exporterat", + "exportFailed": "Kunde inte exportera arkiv", "confirmDelete": "Är du helt säker på att du vill radera ditt konto? Detta kan inte ångras." } }, @@ -362,6 +393,7 @@ "manageTrustedDevices": "Hantera betrodda enheter", "appCompatibility": "Appkompatibilitet", "enterPassword": "Ange ditt lösenord", + "sessionExpired": "Sessionen har gått ut. Logga in igen.", "legacyLoginEnabled": "Föråldrad appinloggning aktiverad", "legacyLoginDisabled": "Föråldrad appinloggning inaktiverad - endast OAuth-appar kan logga in", "failedToUpdatePreference": "Kunde inte uppdatera inställning", @@ -421,6 +453,7 @@ "noRecords": "Inga poster i denna samling", "recordDetails": "Postdetaljer", "rkey": "Postnyckel", + "uri": "URI", "cid": "CID", "value": "Värde", "deleteRecord": "Radera post", @@ -464,9 +497,6 @@ "themeColorsHint": "Lämna tomt för att använda standardfärger.", "primaryLight": "Primär (ljust läge)", "primaryDark": "Primär (mörkt läge)", - "accentLight": "Accent (ljust läge)", - "accentDark": "Accent (mörkt läge)", - "faviconExample": "Favicon-exempel", "configSaved": "Serverkonfiguration sparad", "saving": "Sparar...", "saveConfig": "Spara konfiguration", @@ -508,7 +538,10 @@ "deleteConfirm": "Radera konto @{handle}? Detta kan inte ångras.", "verified": "Verifierad", "unverified": "Ej verifierad", - "deactivated": "Inaktiverad" + "deactivated": "Inaktiverad", + "colorDefault": "{color} (standard)", + "secondaryLight": "Sekundär (Ljust läge)", + "secondaryDark": "Sekundär (Mörkt läge)" }, "oauth": { "login": { @@ -524,7 +557,10 @@ "rememberDevice": "Kom ihåg denna enhet", "passkeyHintChecking": "Kontrollerar nyckelstatus...", "passkeyHintAvailable": "Logga in med din nyckel", - "passkeyHintNotAvailable": "Inga nycklar registrerade för detta konto" + "passkeyHintNotAvailable": "Inga nycklar registrerade för detta konto", + "passkeyHint": "Använd enhetens biometri eller säkerhetsnyckel", + "passwordPlaceholder": "Ange ditt lösenord", + "usePasskey": "Använd nyckel" }, "consent": { "title": "Auktorisera applikation", @@ -740,13 +776,66 @@ "handleNoDots": "Användarnamn kan inte innehålla punkter. Du kan konfigurera ett eget domännamn efter att kontot skapats.", "passkeysNotSupported": "Nycklar stöds inte i denna webbläsare. Skapa ett lösenordsbaserat konto eller använd en webbläsare som stöder nycklar.", "passkeyCancelled": "Nyckelskapande avbröts", - "passkeyFailed": "Nyckelregistrering misslyckades" - } + "passkeyFailed": "Nyckelregistrering misslyckades", + "signalRequired": "Telefonnummer krävs för Signal-verifiering", + "inviteRequired": "Inbjudningskod krävs", + "externalDidRequired": "Extern did:web krävs", + "emailRequired": "E-post krävs för e-postverifiering", + "telegramRequired": "Telegram-användarnamn krävs för Telegram-verifiering", + "externalDidFormat": "Extern DID måste börja med did:web:", + "discordRequired": "Discord-ID krävs för Discord-verifiering" + }, + "whyPasskeyBullet1": "Kan inte nätfiskas eller stjälas vid dataintrång", + "whyPasskeyBullet2": "Använder hårdvarubaserade kryptografiska nycklar", + "whyPasskeyBullet3": "Kräver din biometri eller enhets-PIN för att använda", + "whyPasskeyOnly": "Varför endast nyckel?", + "whyPasskeyOnlyDesc": "Nyckelkonton är säkrare än lösenordsbaserade konton eftersom de:", + "subtitleInitialDidDoc": "Ladda upp ditt DID-dokument för att fortsätta.", + "subtitleUpdatedDidDoc": "Uppdatera ditt DID-dokument med PDS-signeringsnyckeln.", + "subtitleActivating": "Aktiverar ditt konto...", + "subtitleComplete": "Ditt konto har skapats!", + "subtitleCreating": "Skapar ditt konto...", + "subtitleAppPassword": "Spara ditt applösenord för tredjepartsappar.", + "creatingPasskey": "Skapar nyckel...", + "passkeyPrompt": "Klicka på knappen nedan för att skapa din nyckel. Du kommer att uppmanas att använda:", + "passkeyPromptBullet1": "Touch ID eller Face ID", + "passkeyPromptBullet2": "Din enhets PIN-kod eller lösenord", + "passkeyPromptBullet3": "En säkerhetsnyckel (om du har en)", + "identityType": "Identitetstyp", + "identityTypeHint": "Välj hur din decentraliserade identitet ska hanteras.", + "passkeyNameLabel": "Nyckelnamn (valfritt)", + "passkeyNamePlaceholder": "t.ex. MacBook Touch ID", + "passkeyNameHint": "Ett vänligt namn för att identifiera denna nyckel", + "createPasskey": "Skapa nyckel", + "didPlcRecommended": "did:plc (Rekommenderas)", + "didPlcHint": "Portabel identitet som hanteras av PLC Directory", + "didWeb": "did:web", + "didWebHint": "Identitet som lagras på denna PDS (läs varningen nedan)", + "didWebBYOD": "did:web (BYOD)", + "didWebBYODHint": "Ta med din egen domän", + "didWebWarningTitle": "Viktigt: Förstå kompromisserna", + "didWebWarning1": "Permanent koppling till denna PDS:", + "didWebWarning1Detail": "Din identitet {did} är knuten till denna server.", + "didWebWarning2": "Ingen återställningsmekanism:", + "didWebWarning2Detail": "Till skillnad från did:plc har did:web inga rotationsnycklar.", + "didWebWarning3": "Vi förbinder oss till dig:", + "didWebWarning3Detail": "Om du migrerar bort kommer vi att fortsätta servera ett minimalt DID-dokument.", + "didWebWarning4": "Rekommendation:", + "didWebWarning4Detail": "Välj did:plc om du inte har en specifik anledning att föredra did:web.", + "externalDidHint": "Du behöver servera ett DID-dokument på", + "continue": "Fortsätt", + "back": "Tillbaka", + "loading": "Laddar...", + "redirecting": "Omdirigerar till instrumentpanelen...", + "handleDotWarning": "Egna domännamn kan konfigureras efter att kontot skapats.", + "wantTraditional": "Vill du ha ett traditionellt lösenord?", + "registerWithPassword": "Registrera med lösenord" }, "trustedDevices": { "title": "Betrodda enheter", "backToSecurity": "← Säkerhetsinställningar", "description": "Betrodda enheter kan hoppa över tvåfaktorsautentisering vid inloggning. Förtroende beviljas i 30 dagar och förlängs automatiskt när du använder enheten.", + "failedToLoad": "Kunde inte ladda betrodda enheter", "noDevices": "Inga betrodda enheter ännu.", "noDevicesHint": "När du loggar in med tvåfaktorsautentisering aktiverat kan du välja att lita på enheten i 30 dagar.", "lastSeen": "Senast sedd:", diff --git a/frontend/src/locales/zh.json b/frontend/src/locales/zh.json index 02b1001..431656c 100644 --- a/frontend/src/locales/zh.json +++ b/frontend/src/locales/zh.json @@ -30,7 +30,17 @@ "lostPasskey": "丢失通行密钥?", "noAccount": "还没有账户?", "createAccount": "立即注册", - "removeAccount": "从已保存账户中移除" + "removeAccount": "从已保存账户中移除", + "infoSavedAccountsTitle": "已保存账户", + "infoSavedAccountsDesc": "点击账户即可快速登录。您的会话令牌安全存储在此浏览器中。", + "infoNewAccountTitle": "新账户", + "infoNewAccountDesc": "使用登录按钮添加其他账户。点击 × 可从此浏览器中移除已保存的账户。", + "infoSecureSignInTitle": "安全登录", + "infoSecureSignInDesc": "您将被重定向进行安全认证。如果您启用了通行密钥或双重身份验证,也会提示您进行验证。", + "infoStaySignedInTitle": "保持登录", + "infoStaySignedInDesc": "登录后,您的账户将保存在此浏览器中,方便下次快速访问。", + "infoRecoveryTitle": "账户恢复", + "infoRecoveryDesc": "忘记密码或丢失通行密钥?使用登录按钮下方的恢复链接。" }, "verification": { "title": "验证账户", @@ -47,6 +57,17 @@ "register": { "title": "创建账户", "subtitle": "在此 PDS 上创建新账户", + "subtitleKeyChoice": "选择如何设置您的外部 did:web 身份。", + "subtitleInitialDidDoc": "上传您的 DID 文档以继续。", + "subtitleVerify": "验证您的{channel}以继续。", + "subtitleUpdatedDidDoc": "使用 PDS 签名密钥更新您的 DID 文档。", + "subtitleActivating": "正在激活您的账户...", + "subtitleComplete": "您的账户已成功创建!", + "redirecting": "正在跳转到控制台...", + "infoIdentityDesc": "您的身份决定了您的账户在 ATProto 网络中的识别方式。大多数用户应选择标准选项。", + "infoContactDesc": "我们将使用此信息验证您的账户并发送有关账户安全的重要通知。", + "infoNextTitle": "接下来会发生什么?", + "infoNextDesc": "创建账户后,您需要验证联系方式,然后即可使用任何 ATProto 应用程序。", "migrateTitle": "已有 Bluesky 账户?", "migrateDescription": "您可以将现有账户迁移到此 PDS,而无需创建新账户。您的关注者、帖子和身份都会一起迁移。", "migrateLink": "使用 PDS Moover 迁移", @@ -211,12 +232,22 @@ "messages": { "emailCodeSent": "验证码已发送到您的通知渠道", "emailUpdated": "邮箱更新成功", + "emailUpdateFailed": "邮箱更新失败", "handleUpdated": "用户名更新成功", + "handleUpdateFailed": "用户名更新失败", "passwordChanged": "密码更改成功", + "passwordChangeFailed": "密码更改失败", "passwordsMismatch": "两次输入的密码不一致", + "passwordsDoNotMatch": "两次输入的密码不一致", "passwordLength": "密码至少需要8位字符", + "passwordTooShort": "密码至少需要8位字符", "deletionCodeSent": "删除确认码已发送到您的邮箱", + "deletionConfirmationSent": "删除确认码已发送到您的邮箱", + "deletionRequestFailed": "账户删除请求失败", + "deleteConfirmation": "您确定要删除账户吗?此操作无法撤销。", + "deletionFailed": "账户删除失败", "repoExported": "数据导出成功", + "exportFailed": "数据导出失败", "confirmDelete": "您确定要删除账户吗?此操作无法撤销。" } }, @@ -362,6 +393,7 @@ "manageTrustedDevices": "管理受信任设备", "appCompatibility": "应用兼容性", "enterPassword": "输入您的密码", + "sessionExpired": "会话已过期,请重新登录。", "legacyLoginEnabled": "已启用传统应用登录", "legacyLoginDisabled": "已禁用传统应用登录 - 仅 OAuth 应用可登录", "failedToUpdatePreference": "更新偏好设置失败", @@ -421,6 +453,7 @@ "noRecords": "此集合中暂无记录", "recordDetails": "记录详情", "rkey": "记录键", + "uri": "URI", "cid": "CID", "value": "值", "deleteRecord": "删除记录", @@ -463,13 +496,10 @@ "themeColors": "主题颜色", "themeColorsHint": "留空使用默认颜色。", "primaryLight": "主色(浅色模式)", - "primaryLightDefault": "#2c00ff(默认)", + "colorDefault": "{color}(默认)", "primaryDark": "主色(深色模式)", - "primaryDarkDefault": "#7b6bff(默认)", "secondaryLight": "副色(浅色模式)", - "secondaryLightDefault": "#ff2400(默认)", "secondaryDark": "副色(深色模式)", - "secondaryDarkDefault": "#ff6b5b(默认)", "configSaved": "服务器配置已保存", "saving": "保存中...", "saveConfig": "保存配置", @@ -527,7 +557,10 @@ "rememberDevice": "记住此设备", "passkeyHintChecking": "正在检查通行密钥状态...", "passkeyHintAvailable": "使用您的通行密钥登录", - "passkeyHintNotAvailable": "此账户未注册通行密钥" + "passkeyHintNotAvailable": "此账户未注册通行密钥", + "passkeyHint": "使用设备的生物识别或安全密钥", + "passwordPlaceholder": "输入您的密码", + "usePasskey": "使用通行密钥" }, "consent": { "title": "授权应用", @@ -785,6 +818,7 @@ "title": "受信任设备", "backToSecurity": "← 安全设置", "description": "受信任设备可以跳过双重身份验证。信任有效期为30天,使用设备时自动延长。", + "failedToLoad": "加载受信任设备失败", "noDevices": "暂无受信任设备", "noDevicesHint": "开启双重身份验证后登录时,可以选择信任设备30天。", "lastSeen": "最后使用:", diff --git a/frontend/src/main.ts b/frontend/src/main.ts index 77f4a08..6ef7a3a 100644 --- a/frontend/src/main.ts +++ b/frontend/src/main.ts @@ -1,9 +1,9 @@ -import './styles/base.css' -import App from './App.svelte' -import { mount } from 'svelte' +import "./styles/base.css"; +import App from "./App.svelte"; +import { mount } from "svelte"; const app = mount(App, { - target: document.getElementById('app')!, -}) + target: document.getElementById("app")!, +}); -export default app +export default app; diff --git a/frontend/src/routes/Admin.svelte b/frontend/src/routes/Admin.svelte index cfc27e4..9a95c02 100644 --- a/frontend/src/routes/Admin.svelte +++ b/frontend/src/routes/Admin.svelte @@ -6,6 +6,12 @@ import { _ } from '../lib/i18n' import { formatDate, formatDateTime } from '../lib/date' const auth = getAuthState() + const DEFAULT_COLORS = { + primaryLight: '#1A1D1D', + primaryDark: '#E6E8E8', + secondaryLight: '#1A1D1D', + secondaryDark: '#E6E8E8', + } let loading = $state(true) let error = $state(null) let stats = $state<{ @@ -364,7 +370,7 @@ type="text" id="primaryColor" bind:value={primaryColorInput} - placeholder={$_('admin.primaryLightDefault')} + placeholder={$_('admin.colorDefault', { values: { color: DEFAULT_COLORS.primaryLight } })} disabled={serverConfigLoading} /> @@ -381,7 +387,7 @@ type="text" id="primaryColorDark" bind:value={primaryColorDarkInput} - placeholder={$_('admin.primaryDarkDefault')} + placeholder={$_('admin.colorDefault', { values: { color: DEFAULT_COLORS.primaryDark } })} disabled={serverConfigLoading} /> @@ -398,7 +404,7 @@ type="text" id="secondaryColor" bind:value={secondaryColorInput} - placeholder={$_('admin.secondaryLightDefault')} + placeholder={$_('admin.colorDefault', { values: { color: DEFAULT_COLORS.secondaryLight } })} disabled={serverConfigLoading} /> @@ -415,7 +421,7 @@ type="text" id="secondaryColorDark" bind:value={secondaryColorDarkInput} - placeholder={$_('admin.secondaryDarkDefault')} + placeholder={$_('admin.colorDefault', { values: { color: DEFAULT_COLORS.secondaryDark } })} disabled={serverConfigLoading} /> @@ -646,7 +652,7 @@ {/if} diff --git a/frontend/src/routes/OAuthConsent.svelte b/frontend/src/routes/OAuthConsent.svelte index ff7d6e3..49af5e7 100644 --- a/frontend/src/routes/OAuthConsent.svelte +++ b/frontend/src/routes/OAuthConsent.svelte @@ -167,54 +167,60 @@ {:else if consentData} -
- {#if consentData.logo_uri} - - {/if} -

{consentData.client_name || $_('oauth.consent.title')}

-

{$_('oauth.consent.appWantsAccess', { values: { app: '' } })}

- {#if consentData.client_uri} - - {consentData.client_uri} - - {/if} -
+