Page Menu
Home
Phorge
Search
Configure Global Search
Log In
Files
F85826603
No One
Temporary
Actions
View File
Edit File
Delete File
View Transforms
Subscribe
Mute Notifications
Flag For Later
Award Token
Authored By
Unknown
Size
25 KB
Referenced Files
None
Subscribers
None
View Options
diff --git a/src/boot/after_store.js b/src/boot/after_store.js
index ed8fbb0805..abc3515497 100644
--- a/src/boot/after_store.js
+++ b/src/boot/after_store.js
@@ -1,626 +1,626 @@
/* global process */
import vClickOutside from 'click-outside-vue3'
import { get, set } from 'lodash'
import { createApp } from 'vue'
import { createRouter, createWebHistory } from 'vue-router'
import VueVirtualScroller from 'vue-virtual-scroller'
import 'vue-virtual-scroller/dist/vue-virtual-scroller.css'
import { config } from '@fortawesome/fontawesome-svg-core'
import {
FontAwesomeIcon,
FontAwesomeLayers,
} from '@fortawesome/vue-fontawesome'
config.autoAddCss = false
import App from '../App.vue'
import backendInteractorService from '../services/backend_interactor_service/backend_interactor_service.js'
import FaviconService from '../services/favicon_service/favicon_service.js'
import { applyStyleConfig } from '../services/style_setter/style_setter.js'
import { initServiceWorker, updateFocus } from '../services/sw/sw.js'
import {
windowHeight,
windowWidth,
} from '../services/window_utils/window_utils'
import routes from './routes'
import { useAnnouncementsStore } from 'src/stores/announcements.js'
import { useAuthFlowStore } from 'src/stores/auth_flow.js'
import { useI18nStore } from 'src/stores/i18n.js'
import { useInstanceStore } from 'src/stores/instance.js'
import { useInterfaceStore } from 'src/stores/interface.js'
import { useOAuthStore } from 'src/stores/oauth.js'
import { useSyncConfigStore } from 'src/stores/sync_config.js'
import VBodyScrollLock from 'src/directives/body_scroll_lock'
import {
instanceDefaultConfig,
staticOrApiConfigDefault,
} from 'src/modules/default_config_state.js'
let staticInitialResults = null
const parsedInitialResults = () => {
if (!document.getElementById('initial-results')) {
return null
}
if (!staticInitialResults) {
staticInitialResults = JSON.parse(
document.getElementById('initial-results').textContent,
)
}
return staticInitialResults
}
const decodeUTF8Base64 = (data) => {
const rawData = atob(data)
const array = Uint8Array.from([...rawData].map((char) => char.charCodeAt(0)))
const text = new TextDecoder().decode(array)
return text
}
const preloadFetch = async (request) => {
const data = parsedInitialResults()
if (!data || !data[request]) {
return window.fetch(request)
}
const decoded = decodeUTF8Base64(data[request])
const requestData = JSON.parse(decoded)
return {
ok: true,
json: () => requestData,
text: () => requestData,
}
}
const getInstanceConfig = async ({ store }) => {
try {
const res = await preloadFetch('/api/v1/instance')
if (res.ok) {
const data = await res.json()
const textlimit = data.max_toot_chars
const vapidPublicKey = data.pleroma.vapid_public_key
useInstanceStore().set({
path: 'featureSet.pleromaExtensionsAvailable',
value: data.pleroma,
})
useInstanceStore().set({
path: 'textlimit',
value: textlimit,
})
useInstanceStore().set({
path: 'accountApprovalRequired',
value: data.approval_required,
})
useInstanceStore().set({
path: 'birthdayRequired',
value: !!data.pleroma?.metadata.birthday_required,
})
useInstanceStore().set({
path: 'birthdayMinAge',
value: data.pleroma?.metadata.birthday_min_age || 0,
})
if (vapidPublicKey) {
useInstanceStore().set({
path: 'vapidPublicKey',
value: vapidPublicKey,
})
}
} else {
throw res
}
} catch (error) {
console.error('Could not load instance config, potentially fatal')
console.error(error)
}
// We should check for scrobbles support here but it requires userId
// so instead we check for it where it's fetched (statuses.js)
}
const getBackendProvidedConfig = async () => {
try {
const res = await window.fetch('/api/pleroma/frontend_configurations')
if (res.ok) {
const data = await res.json()
return data.pleroma_fe
} else {
throw res
}
} catch (error) {
console.error(
'Could not load backend-provided frontend config, potentially fatal',
)
console.error(error)
}
}
const getStaticConfig = async () => {
try {
const res = await window.fetch('/static/config.json')
if (res.ok) {
return res.json()
} else {
throw res
}
} catch (error) {
console.warn('Failed to load static/config.json, continuing without it.')
console.warn(error)
return {}
}
}
const setSettings = async ({ apiConfig, staticConfig, store }) => {
const overrides = window.___pleromafe_dev_overrides || {}
const env = window.___pleromafe_mode.NODE_ENV
// This takes static config and overrides properties that are present in apiConfig
let config = {}
if (overrides.staticConfigPreference && env === 'development') {
console.warn('OVERRIDING API CONFIG WITH STATIC CONFIG')
config = { ...apiConfig, ...staticConfig }
} else {
config = { ...staticConfig, ...apiConfig }
}
const copyInstanceIdentityOption = (path) => {
if (get(config, path) !== undefined) {
useInstanceStore().set({
path: `instanceIdentity.${path}`,
value: get(config, path),
})
}
}
console.log(config)
const copyInstancePrefOption = (path) => {
if (get(config, path) !== undefined) {
useInstanceStore().set({
path: `prefsStorage.${path}`,
value: get(config, path),
})
}
}
Object.keys(staticOrApiConfigDefault).forEach(copyInstanceIdentityOption)
Object.keys(instanceDefaultConfig).forEach(copyInstancePrefOption)
useAuthFlowStore().setInitialStrategy(config.loginMethod)
}
const getTOS = async ({ store }) => {
try {
const res = await window.fetch('/static/terms-of-service.html')
if (res.ok) {
const html = await res.text()
useInstanceStore().set({ path: 'tos', value: html })
} else {
throw res
}
} catch (e) {
console.warn("Can't load TOS\n", e)
}
}
const getInstancePanel = async ({ store }) => {
try {
const res = await preloadFetch('/instance/panel.html')
if (res.ok) {
const html = await res.text()
useInstanceStore().set({
path: 'instanceSpecificPanelContent',
value: html,
})
} else {
throw res
}
} catch (e) {
console.warn("Can't load instance panel\n", e)
}
}
const getStickers = async ({ store }) => {
try {
const res = await window.fetch('/static/stickers.json')
if (res.ok) {
const values = await res.json()
const stickers = (
await Promise.all(
Object.entries(values).map(async ([name, path]) => {
const resPack = await window.fetch(path + 'pack.json')
let meta = {}
if (resPack.ok) {
meta = await resPack.json()
}
return {
pack: name,
path,
meta,
}
}),
)
).sort((a, b) => {
return a.meta.title.localeCompare(b.meta.title)
})
useInstanceStore().set({ path: 'stickers', value: stickers })
} else {
throw res
}
} catch (e) {
console.warn("Can't load stickers\n", e)
}
}
const getAppSecret = async ({ store }) => {
const oauth = useOAuthStore()
if (oauth.userToken) {
store.commit(
'setBackendInteractor',
backendInteractorService(oauth.getToken),
)
}
}
const resolveStaffAccounts = ({ store, accounts }) => {
const nicknames = accounts.map((uri) => uri.split('/').pop())
useInstanceStore().set({
path: 'staffAccounts',
value: nicknames,
})
}
const getNodeInfo = async ({ store }) => {
try {
let res = await preloadFetch('/nodeinfo/2.1.json')
if (!res.ok) res = await preloadFetch('/nodeinfo/2.0.json')
if (res.ok) {
const data = await res.json()
const metadata = data.metadata
const features = metadata.features
useInstanceStore().set({
path: 'localBubbleInstances',
value: metadata.localBubbleInstances ?? [],
})
useInstanceStore().set({
path: 'instanceIdentity.name',
value: metadata.nodeName,
})
useInstanceStore().set({
path: 'registrationOpen',
value: data.openRegistrations,
})
useInstanceStore().set({
path: 'restrictedNicknames',
value: metadata.restrictedNicknames,
})
useInstanceStore().set({
path: 'featureSet.mediaProxyAvailable',
value: features.includes('media_proxy'),
})
useInstanceStore().set({
path: 'featureSet.safeDM',
value: features.includes('safe_dm_mentions'),
})
useInstanceStore().set({
path: 'featureSet.shoutAvailable',
value: features.includes('chat'),
})
useInstanceStore().set({
path: 'featureSet.pleromaChatMessagesAvailable',
value: features.includes('pleroma_chat_messages'),
})
useInstanceStore().set({
path: 'featureSet.pleromaCustomEmojiReactionsAvailable',
value:
features.includes('pleroma_custom_emoji_reactions') ||
features.includes('custom_emoji_reactions'),
})
useInstanceStore().set({
path: 'featureSet.pleromaBookmarkFoldersAvailable',
value: features.includes('pleroma:bookmark_folders'),
})
useInstanceStore().set({
path: 'featureSet.gopherAvailable',
value: features.includes('gopher'),
})
useInstanceStore().set({
path: 'featureSet.pollsAvailable',
value: features.includes('polls'),
})
useInstanceStore().set({
path: 'featureSet.editingAvailable',
value: features.includes('editing'),
})
useInstanceStore().set({
path: 'featureSet.mailerEnabled',
value: metadata.mailerEnabled,
})
useInstanceStore().set({
path: 'featureSet.quotingAvailable',
value: features.includes('quote_posting'),
})
useInstanceStore().set({
path: 'featureSet.groupActorAvailable',
value: features.includes('pleroma:group_actors'),
})
useInstanceStore().set({
path: 'featureSet.blockExpiration',
value: features.includes('pleroma:block_expiration'),
})
useInstanceStore().set({
path: 'featureSet.localBubble',
value: Array.isArray(metadata.localBubbleInstances),
})
const uploadLimits = metadata.uploadLimits
useInstanceStore().set({
path: 'limits.uploadlimit',
value: parseInt(uploadLimits.general),
})
useInstanceStore().set({
path: 'limits.avatarlimit',
value: parseInt(uploadLimits.avatar),
})
useInstanceStore().set({
path: 'limits.backgroundlimit',
value: parseInt(uploadLimits.background),
})
useInstanceStore().set({
path: 'limits.bannerlimit',
value: parseInt(uploadLimits.banner),
})
useInstanceStore().set({
path: 'limits.fieldsLimits',
value: metadata.fieldsLimits,
})
useInstanceStore().set({
path: 'limits.pollLimits',
value: metadata.pollLimits,
})
useInstanceStore().set({
path: 'featureSet.postFormats',
value: metadata.postFormats,
})
const suggestions = metadata.suggestions
useInstanceStore().set({
path: 'featureSet.suggestionsEnabled',
value: suggestions.enabled,
})
useInstanceStore().set({
path: 'featureSet.suggestionsWeb',
value: suggestions.web,
})
//
const software = data.software
useInstanceStore().set({
path: 'backendVersion',
value: software.version,
})
useInstanceStore().set({
path: 'backendRepository',
value: software.repository,
})
useInstanceStore().set({ path: 'private', value: metadata.private })
const frontendVersion = window.___pleromafe_commit_hash
useInstanceStore().set({
path: 'frontendVersion',
value: frontendVersion,
})
const federation = metadata.federation
useInstanceStore().set({
path: 'featureSet.tagPolicyAvailable',
value:
typeof federation.mrf_policies === 'undefined'
? false
: metadata.federation.mrf_policies.includes('TagPolicy'),
})
useInstanceStore().set({
path: 'federationPolicy',
value: federation,
})
useInstanceStore().set({
path: 'federating',
value:
typeof federation.enabled === 'undefined' ? true : federation.enabled,
})
const accountActivationRequired = metadata.accountActivationRequired
useInstanceStore().set({
path: 'accountActivationRequired',
value: accountActivationRequired,
})
const accounts = metadata.staffAccounts
resolveStaffAccounts({ store, accounts })
} else {
throw res
}
} catch (e) {
console.warn('Could not load nodeinfo')
console.warn(e)
}
}
const setConfig = async ({ store }) => {
// apiConfig, staticConfig
const configInfos = await Promise.all([
getBackendProvidedConfig({ store }),
getStaticConfig(),
])
const apiConfig = configInfos[0]
const staticConfig = configInfos[1]
getAppSecret({ store })
await setSettings({ store, apiConfig, staticConfig })
}
const checkOAuthToken = async ({ store }) => {
const oauth = useOAuthStore()
- if (oauth.getUserToken) {
+ if (oauth.userToken) {
return store.dispatch('loginUser', oauth.getUserToken)
}
return Promise.resolve()
}
const afterStoreSetup = async ({ pinia, store, storageError, i18n }) => {
const app = createApp(App)
// Must have app use pinia before we do anything that touches the store
// https://pinia.vuejs.org/core-concepts/plugins.html#Introduction
// "Plugins are only applied to stores created after the plugins themselves, and after pinia is passed to the app, otherwise they won't be applied."
app.use(pinia)
const waitForAllStoresToLoad = async () => {
// the stores that do not persist technically do not need to be awaited here,
// but that involves either hard-coding the stores in some place (prone to errors)
// or writing another vite plugin to analyze which stores needs persisting (++load time)
const allStores = import.meta.glob('../stores/*.js', { eager: true })
if (process.env.NODE_ENV === 'development') {
// do some checks to avoid common errors
if (!Object.keys(allStores).length) {
throw new Error(
'No stores are available. Check the code in src/boot/after_store.js',
)
}
}
await Promise.all(
Object.entries(allStores).map(async ([name, mod]) => {
const isStoreName = (name) => name.startsWith('use')
if (process.env.NODE_ENV === 'development') {
if (Object.keys(mod).filter(isStoreName).length !== 1) {
throw new Error(
'Each store file must export exactly one store as a named export. Check your code in src/stores/',
)
}
}
const storeFuncName = Object.keys(mod).find(isStoreName)
if (storeFuncName && typeof mod[storeFuncName] === 'function') {
const p = mod[storeFuncName]().$persistLoaded
if (!(p instanceof Promise)) {
throw new Error(
`${name} store's $persistLoaded is not a Promise. The persist plugin is not applied.`,
)
}
await p
} else {
throw new Error(
`Store module ${name} does not export a 'use...' function`,
)
}
}),
)
}
try {
await waitForAllStoresToLoad()
} catch (e) {
console.error('Cannot load stores:', e)
storageError = e
}
if (storageError) {
useInterfaceStore().pushGlobalNotice({
messageKey: 'errors.storage_unavailable',
level: 'error',
})
}
useInterfaceStore().setLayoutWidth(windowWidth())
useInterfaceStore().setLayoutHeight(windowHeight())
FaviconService.initFaviconService()
initServiceWorker(store)
window.addEventListener('focus', () => updateFocus())
const overrides = window.___pleromafe_dev_overrides || {}
const server =
typeof overrides.target !== 'undefined'
? overrides.target
: window.location.origin
useInstanceStore().set({ path: 'server', value: server })
await setConfig({ store })
try {
await useInterfaceStore()
.applyTheme()
.catch((e) => {
console.error('Error setting theme', e)
})
} catch (e) {
window.splashError(e)
return Promise.reject(e)
}
applyStyleConfig(useSyncConfigStore().mergedConfig)
// Now we can try getting the server settings and logging in
// Most of these are preloaded into the index.html so blocking is minimized
await Promise.all([
checkOAuthToken({ store }),
getInstancePanel({ store }),
getNodeInfo({ store }),
getInstanceConfig({ store }),
]).catch((e) => Promise.reject(e))
// Start fetching things that don't need to block the UI
store.dispatch('fetchMutes')
store.dispatch('loadDrafts')
useAnnouncementsStore().startFetchingAnnouncements()
getTOS({ store })
getStickers({ store })
const router = createRouter({
history: createWebHistory(),
routes: routes(store),
scrollBehavior: (to, _from, savedPosition) => {
if (to.matched.some((m) => m.meta.dontScroll)) {
return false
}
return savedPosition || { left: 0, top: 0 }
},
})
useI18nStore().setI18n(i18n)
app.use(router)
app.use(store)
app.use(i18n)
// Little thing to get out of invalid theme state
window.resetThemes = () => {
useInterfaceStore().resetThemeV3()
useInterfaceStore().resetThemeV3Palette()
useInterfaceStore().resetThemeV2()
}
app.use(vClickOutside)
app.use(VBodyScrollLock)
app.use(VueVirtualScroller)
app.component('FAIcon', FontAwesomeIcon)
app.component('FALayers', FontAwesomeLayers)
// remove after vue 3.3
app.config.unwrapInjectedRef = true
app.mount('#app')
return app
}
export default afterStoreSetup
diff --git a/src/components/mfa_form/totp_form.js b/src/components/mfa_form/totp_form.js
index ab7754415d..99ea2b85e4 100644
--- a/src/components/mfa_form/totp_form.js
+++ b/src/components/mfa_form/totp_form.js
@@ -1,65 +1,63 @@
-import { mapActions, mapState as mapPiniaState, mapStores } from 'pinia'
-import { mapState } from 'vuex'
+import { mapActions, mapState, mapStores } from 'pinia'
import mfaApi from '../../services/new_api/mfa.js'
import { useAuthFlowStore } from 'src/stores/auth_flow.js'
import { useOAuthStore } from 'src/stores/oauth.js'
+import { useInstanceStore } from 'src/stores/instance.js'
import { library } from '@fortawesome/fontawesome-svg-core'
import { faTimes } from '@fortawesome/free-solid-svg-icons'
library.add(faTimes)
export default {
data: () => ({
code: null,
error: false,
}),
computed: {
- ...mapPiniaState(useAuthFlowStore, {
+ ...mapState(useAuthFlowStore, {
authSettings: (store) => store.settings,
}),
+ ...mapState(useInstanceStore, ['server']),
...mapStores(useOAuthStore),
- ...mapState({
- instance: 'instance',
- }),
},
methods: {
...mapActions(useAuthFlowStore, ['requireRecovery', 'abortMFA', 'login']),
clearError() {
this.error = false
},
focusOnCodeInput() {
const codeInput = this.$refs.codeInput
codeInput.focus()
codeInput.setSelectionRange(0, codeInput.value.length)
},
submit() {
const { clientId, clientSecret } = this.oauthStore
const data = {
clientId,
clientSecret,
- instance: this.instance.server,
+ instance: this.server,
mfaToken: this.authSettings.mfa_token,
code: this.code,
}
mfaApi.verifyOTPCode(data).then((result) => {
if (result.error) {
this.error = result.error
this.code = null
this.focusOnCodeInput()
return
}
this.login(result).then(() => {
this.$router.push({ name: 'friends' })
})
})
},
},
}
diff --git a/src/stores/oauth.js b/src/stores/oauth.js
index ea5a4bfacd..47eee00bcb 100644
--- a/src/stores/oauth.js
+++ b/src/stores/oauth.js
@@ -1,160 +1,158 @@
import { defineStore } from 'pinia'
+import { useInstanceStore } from 'src/stores/instance.js'
import {
createApp,
getClientToken,
verifyAppToken,
} from 'src/services/new_api/oauth.js'
// status codes about verifyAppToken (GET /api/v1/apps/verify_credentials)
const isAppTokenRejected = (error) =>
// Pleroma API docs say it returns 422 when unauthorized
error.statusCode === 422 ||
// but it actually returns 400 (as of 2.9.0)
// NOTE: don't try to match against the error message, it is translatable
error.statusCode === 400 ||
// and Mastodon docs say it returns 401
error.statusCode === 401
// status codes about getAppToken (GET /oauth/token)
const isClientDataRejected = (error) =>
// Mastodon docs say it returns 401
error.statusCode === 401 ||
// but Pleroma actually returns 400 (as of 2.9.0)
// NOTE: don't try to match against the error message, it is translatable
error.statusCode === 400
export const useOAuthStore = defineStore('oauth', {
state: () => ({
clientId: false,
clientSecret: false,
/* App token is authentication for app without any user, used mostly for
* MastoAPI's registration of new users, stored so that we can fall back to
* it on logout
*/
appToken: false,
/* User token is authentication for app with user, this is for every calls
* that need authorized user to be successful (i.e. posting, liking etc)
*/
userToken: false,
}),
getters: {
getToken() {
return this.userToken || this.appToken
},
- getUserToken() {
- return this.userToken
- },
},
actions: {
setClientData({ clientId, clientSecret }) {
this.clientId = clientId
this.clientSecret = clientSecret
},
setAppToken(token) {
this.appToken = token
},
setToken(token) {
this.userToken = token
},
clearToken() {
this.userToken = false
},
async createApp() {
const { state } = window.vuex
- const instance = state.instance.server
+ const instance = useInstanceStore().server
const app = await createApp(instance)
this.setClientData(app)
return app
},
/// Use this if you want to get the client id and secret but are not interested
/// in whether they are valid.
/// @return {{ clientId: string, clientSecret: string }} An object representing the app
async ensureApp() {
if (this.clientId && this.clientSecret) {
return {
clientId: this.clientId,
clientSecret: this.clientSecret,
}
} else {
return this.createApp()
}
},
async getAppToken() {
const { state } = window.vuex
- const instance = state.instance.server
+ const instance = useInstanceStore().server
const res = await getClientToken({
clientId: this.clientId,
clientSecret: this.clientSecret,
instance,
})
this.setAppToken(res.access_token)
return res.access_token
},
/// Use this if you want to ensure the app is still valid to use.
/// @return {string} The access token to the app (not attached to any user)
async ensureAppToken() {
const { state } = window.vuex
if (this.appToken) {
try {
await verifyAppToken({
- instance: state.instance.server,
+ instance: useInstanceStore().server,
appToken: this.appToken,
})
return this.appToken
} catch (e) {
if (!isAppTokenRejected(e)) {
// The server did not reject our token, but we encountered other problems. Maybe the server is down.
throw e
} else {
// The app token is rejected, so it is no longer useful.
this.setAppToken(false)
}
}
}
// appToken is not available, or is rejected: try to get a new one.
// First, make sure the client id and client secret are filled.
try {
await this.ensureApp()
} catch (e) {
console.error('Cannot create app', e)
throw e
}
// Note that at this step, the client id and secret may be invalid
// (because the backend may have already deleted the app due to no user login)
try {
return await this.getAppToken()
} catch (e) {
if (!isClientDataRejected(e)) {
// Non-credentials problem, fail fast
console.error('Cannot get app token', e)
throw e
} else {
// the client id and secret are invalid, so we should clear them
// and re-create our app
this.setClientData({
clientId: false,
clientSecret: false,
})
await this.createApp()
// try once again to get the token
return await this.getAppToken()
}
}
},
},
persist: {
afterLoad(state) {
// state.token is userToken with older name, coming from persistent state
if (state.token && !state.userToken) {
state.userToken = state.token
}
if ('token' in state) {
delete state.token
}
return state
},
},
})
File Metadata
Details
Attached
Mime Type
text/x-diff
Expires
Fri, Oct 30, 8:26 AM (18 h, 26 m)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
1799882
Default Alt Text
(25 KB)
Attached To
Mode
rPUFE pleroma-fe-upstream
Attached
Detach File
Event Timeline