|
|
|
@ -107,7 +107,7 @@ export const cError: Writable<string | null> = writable(null)
|
|
|
|
|
class ApiClient {
|
|
|
|
|
private viewCookieName: string
|
|
|
|
|
private baseUrl: string
|
|
|
|
|
private lastAtUpdate = new Date(0) // Refreshing the page wipes access and CSRF tokens from memory -> Rotation needed
|
|
|
|
|
private lastAtUpdate = new Date(0)
|
|
|
|
|
private lastCsrfUpdate = new Date(0)
|
|
|
|
|
private refreshInProgress = false
|
|
|
|
|
private activeVersion = -1
|
|
|
|
@ -123,7 +123,7 @@ class ApiClient {
|
|
|
|
|
private async handleRequest<T>(
|
|
|
|
|
fn: () => Promise<T>,
|
|
|
|
|
options: { useBearerAuth: boolean }
|
|
|
|
|
): Promise<T | null> {
|
|
|
|
|
): Promise<T | undefined> {
|
|
|
|
|
isPending.set(true)
|
|
|
|
|
cError.set(null)
|
|
|
|
|
|
|
|
|
@ -137,21 +137,18 @@ class ApiClient {
|
|
|
|
|
try {
|
|
|
|
|
await this.checkAndRefreshAccessToken()
|
|
|
|
|
} catch (err) {
|
|
|
|
|
console.log("[REQ] Refresh attempt not successful")
|
|
|
|
|
console.log("refresh attempt not successful")
|
|
|
|
|
await this.handleLocalLogout()
|
|
|
|
|
throw new Error("Session expired, please authenticate again.")
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return await fn()
|
|
|
|
|
} catch (err) {
|
|
|
|
|
cError.set(err instanceof Error ? err.message : "Unknown error")
|
|
|
|
|
console.log(`[ERR] ${get(cError)}`)
|
|
|
|
|
console.log(`error: ${get(cError)}`)
|
|
|
|
|
} finally {
|
|
|
|
|
isPending.set(false)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return null
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Should be attached to routes that handle authentication with the bearer token (access token)
|
|
|
|
@ -164,12 +161,12 @@ class ApiClient {
|
|
|
|
|
// This should never happen due to the token expiration checks we make client-side,
|
|
|
|
|
// but it's still good to have as a fallback
|
|
|
|
|
try {
|
|
|
|
|
console.log("[RES] Unexpected 401 caught, attempting to refresh...")
|
|
|
|
|
console.log("unexpected 401 caught, attempting refresh")
|
|
|
|
|
await this.checkAndRefreshAccessToken()
|
|
|
|
|
} catch (err) {
|
|
|
|
|
const errMsg = err instanceof Error ? err.message : "Unknown error"
|
|
|
|
|
console.log("refresh attempt not successful")
|
|
|
|
|
await this.handleLocalLogout()
|
|
|
|
|
throw new Error(errMsg)
|
|
|
|
|
throw new Error("Session expired, please authenticate again.")
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
@ -195,16 +192,20 @@ class ApiClient {
|
|
|
|
|
const timeSinceUpdate = Date.now() - this.lastAtUpdate.getTime()
|
|
|
|
|
const needsRefresh = timeSinceUpdate > AT_EXP_MS - REFRESH_BUF
|
|
|
|
|
|
|
|
|
|
console.log(`timeSinceUpdate: ${timeSinceUpdate}`)
|
|
|
|
|
|
|
|
|
|
if (needsRefresh) {
|
|
|
|
|
console.log(`[AUTH] Running token refresh attempt (timeSinceUpdate=${timeSinceUpdate})`)
|
|
|
|
|
console.log("running token refresh attempt")
|
|
|
|
|
|
|
|
|
|
this.refreshInProgress = true
|
|
|
|
|
await this.refreshAccessToken()
|
|
|
|
|
this.refreshInProgress = false
|
|
|
|
|
} else {
|
|
|
|
|
console.log("no need to rotate tokens")
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private async refreshAccessToken(): Promise<void | null> {
|
|
|
|
|
private async refreshAccessToken(): Promise<void> {
|
|
|
|
|
return this.handleRequest(
|
|
|
|
|
async () => {
|
|
|
|
|
const response = await fetch(`${this.baseUrl}/auth/cookie/refresh`, {
|
|
|
|
@ -234,7 +235,7 @@ class ApiClient {
|
|
|
|
|
const needsRefresh = timeSinceUpdate > CSRF_EXP_MS - REFRESH_BUF
|
|
|
|
|
|
|
|
|
|
if (!token || needsRefresh) {
|
|
|
|
|
console.log("[AUTH] Refreshing CSRF token")
|
|
|
|
|
console.log("refreshing csrf token")
|
|
|
|
|
await this.refreshCsrfToken()
|
|
|
|
|
token = get(csrfToken)
|
|
|
|
|
}
|
|
|
|
@ -242,7 +243,7 @@ class ApiClient {
|
|
|
|
|
return { "X-Csrf-Token": token || "" }
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private async refreshCsrfToken(): Promise<void | null> {
|
|
|
|
|
private async refreshCsrfToken(): Promise<void> {
|
|
|
|
|
return this.handleRequest(
|
|
|
|
|
async () => {
|
|
|
|
|
const response = await fetch(`${this.baseUrl}/auth/cookie/csrf`, {
|
|
|
|
@ -262,7 +263,7 @@ class ApiClient {
|
|
|
|
|
)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private async handleLocalLogout(): Promise<void | null> {
|
|
|
|
|
private async handleLocalLogout(): Promise<void> {
|
|
|
|
|
this.lastAtUpdate = new Date(0)
|
|
|
|
|
this.lastCsrfUpdate = new Date(0)
|
|
|
|
|
|
|
|
|
@ -285,7 +286,7 @@ class ApiClient {
|
|
|
|
|
const viewCookie = this.getCookieValue(this.viewCookieName)
|
|
|
|
|
|
|
|
|
|
if (!viewCookie) {
|
|
|
|
|
console.log("[AUTH] View cookie not found")
|
|
|
|
|
console.log("view cookie not found")
|
|
|
|
|
return false
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
@ -293,11 +294,14 @@ class ApiClient {
|
|
|
|
|
const expirationTimestamp = parseInt(value, 10)
|
|
|
|
|
|
|
|
|
|
if (isNaN(expirationTimestamp)) {
|
|
|
|
|
console.log(`[ERR] Invalid view cookie expiration timestamp: ${value}`)
|
|
|
|
|
console.log(`invalid expiration timestamp: ${value}`)
|
|
|
|
|
return false
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return now < new Date(expirationTimestamp * 1000)
|
|
|
|
|
const expirationDate = new Date(expirationTimestamp * 1000)
|
|
|
|
|
console.log(`auth cookie expiration: ${expirationDate}`)
|
|
|
|
|
|
|
|
|
|
return now < expirationDate
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private deleteViewCookie() {
|
|
|
|
@ -374,12 +378,12 @@ class ApiClient {
|
|
|
|
|
private joinDeserializedVersion(
|
|
|
|
|
noteID: string,
|
|
|
|
|
apiResponse: ApiFullVersionResponse
|
|
|
|
|
): FullNote | null {
|
|
|
|
|
): FullNote | undefined {
|
|
|
|
|
// Cache lookups are safe here due to this always being called *after* fetching the actual `FullNote`
|
|
|
|
|
const cachedNote = this.loadedNotesCache.get(noteID)
|
|
|
|
|
|
|
|
|
|
if (!cachedNote) {
|
|
|
|
|
return null
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return {
|
|
|
|
@ -395,7 +399,7 @@ class ApiClient {
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public async register(username: string, password: string): Promise<void | null> {
|
|
|
|
|
public async register(username: string, password: string): Promise<void> {
|
|
|
|
|
return this.handleRequest(
|
|
|
|
|
async () => {
|
|
|
|
|
const response = await fetch(`${this.baseUrl}/auth/signup`, {
|
|
|
|
@ -404,21 +408,20 @@ class ApiClient {
|
|
|
|
|
body: JSON.stringify({ username, password })
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
// Can't overwrite the function parameter
|
|
|
|
|
// Can't overwrite `username` parameter
|
|
|
|
|
const data = await this.handleResponse<{
|
|
|
|
|
id: string
|
|
|
|
|
username: string
|
|
|
|
|
}>(response, { useBearerAuth: false })
|
|
|
|
|
|
|
|
|
|
console.log(`[USER] Registration of user '${data.username}' successful`)
|
|
|
|
|
|
|
|
|
|
console.log(`${data.username} -> ${data.id}`)
|
|
|
|
|
await goto("/login")
|
|
|
|
|
},
|
|
|
|
|
{ useBearerAuth: false }
|
|
|
|
|
)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public async login(username: string, password: string): Promise<void | null> {
|
|
|
|
|
public async login(username: string, password: string): Promise<void> {
|
|
|
|
|
return this.handleRequest(
|
|
|
|
|
async () => {
|
|
|
|
|
const response = await fetch(`${this.baseUrl}/auth/login`, {
|
|
|
|
@ -441,7 +444,7 @@ class ApiClient {
|
|
|
|
|
)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public async logout(): Promise<void | null> {
|
|
|
|
|
public async logout(): Promise<void> {
|
|
|
|
|
return this.handleRequest(
|
|
|
|
|
async () => {
|
|
|
|
|
const response = await fetch(`${this.baseUrl}/auth/logout`, {
|
|
|
|
@ -453,7 +456,7 @@ class ApiClient {
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
if (response.status === 204) {
|
|
|
|
|
console.log("[USER] Logout successful")
|
|
|
|
|
console.log("logout successful")
|
|
|
|
|
await this.handleLocalLogout()
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
@ -465,7 +468,7 @@ class ApiClient {
|
|
|
|
|
)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public async getCurrentUser(): Promise<void | null> {
|
|
|
|
|
public async getCurrentUser(): Promise<void> {
|
|
|
|
|
return this.handleRequest(
|
|
|
|
|
async () => {
|
|
|
|
|
const response = await fetch(`${this.baseUrl}/auth/me`, {
|
|
|
|
@ -476,16 +479,15 @@ class ApiClient {
|
|
|
|
|
const data = await this.handleResponse<ApiUserResponse>(response, { useBearerAuth: false })
|
|
|
|
|
const user = this.deserializeUser(data)
|
|
|
|
|
|
|
|
|
|
console.log(user)
|
|
|
|
|
|
|
|
|
|
currentUser.set(user)
|
|
|
|
|
},
|
|
|
|
|
{ useBearerAuth: true }
|
|
|
|
|
)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public async updateCurrentUserPassword(
|
|
|
|
|
oldPassword: string,
|
|
|
|
|
newPassword: string
|
|
|
|
|
): Promise<void | null> {
|
|
|
|
|
public async updateCurrentUserPassword(oldPassword: string, newPassword: string): Promise<void> {
|
|
|
|
|
return this.handleRequest(
|
|
|
|
|
async () => {
|
|
|
|
|
const data = {
|
|
|
|
@ -500,21 +502,21 @@ class ApiClient {
|
|
|
|
|
},
|
|
|
|
|
body: JSON.stringify(data)
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
const { accessToken: token, user } = await this.handleResponse<{
|
|
|
|
|
accessToken: string
|
|
|
|
|
user: User
|
|
|
|
|
}>(response, { useBearerAuth: false })
|
|
|
|
|
|
|
|
|
|
accessToken.set(token)
|
|
|
|
|
currentUser.set(user || null)
|
|
|
|
|
this.lastAtUpdate = new Date()
|
|
|
|
|
|
|
|
|
|
console.log(user)
|
|
|
|
|
},
|
|
|
|
|
{ useBearerAuth: true }
|
|
|
|
|
)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public async deleteCurrentUser(password: string): Promise<void | null> {
|
|
|
|
|
public async deleteCurrentUser(password: string): Promise<void> {
|
|
|
|
|
return this.handleRequest(
|
|
|
|
|
async () => {
|
|
|
|
|
const response = await fetch(`${this.baseUrl}/auth/owner`, {
|
|
|
|
@ -527,7 +529,7 @@ class ApiClient {
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
if (response.status === 204) {
|
|
|
|
|
console.log("[USER] Deletion successful")
|
|
|
|
|
console.log("deletion successful")
|
|
|
|
|
await this.handleLocalLogout()
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
@ -539,7 +541,7 @@ class ApiClient {
|
|
|
|
|
)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public async adminListAll(): Promise<User[] | null> {
|
|
|
|
|
public async adminListAll(): Promise<User[] | undefined> {
|
|
|
|
|
const user = get(currentUser)
|
|
|
|
|
if (!user || !user.isAdmin) {
|
|
|
|
|
throw new Error("Admin privileges required.")
|
|
|
|
@ -557,7 +559,7 @@ class ApiClient {
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
const users = await this.handleResponse<User[]>(response, { useBearerAuth: false })
|
|
|
|
|
console.log(`[ADMIN] Got ${users.length} user results`)
|
|
|
|
|
console.log(`admin: got ${users.length} user results`)
|
|
|
|
|
|
|
|
|
|
return users
|
|
|
|
|
},
|
|
|
|
@ -565,7 +567,7 @@ class ApiClient {
|
|
|
|
|
)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public async adminDeleteUser(userID: string): Promise<void | null> {
|
|
|
|
|
public async adminDeleteUser(userID: string): Promise<void> {
|
|
|
|
|
const user = get(currentUser)
|
|
|
|
|
if (!user || !user.isAdmin) {
|
|
|
|
|
throw new Error("Admin privileges required.")
|
|
|
|
@ -585,7 +587,7 @@ class ApiClient {
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
if (response.status === 204) {
|
|
|
|
|
console.log(`[ADMIN] Deletion of user '${userID}' successful`)
|
|
|
|
|
console.log("admin: deletion successful")
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
@ -595,7 +597,7 @@ class ApiClient {
|
|
|
|
|
)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public async listNotes(): Promise<NoteMetadata[] | null> {
|
|
|
|
|
public async listNotes(): Promise<NoteMetadata[] | undefined> {
|
|
|
|
|
return this.handleRequest(
|
|
|
|
|
async () => {
|
|
|
|
|
const params = new URLSearchParams()
|
|
|
|
@ -616,7 +618,7 @@ class ApiClient {
|
|
|
|
|
notes = this.deserializeNoteMetadatas(data)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
console.log(`[NOTE] Got ${notes.length} note metadata results`)
|
|
|
|
|
console.log(`got ${notes.length} note metadata results`)
|
|
|
|
|
|
|
|
|
|
return notes
|
|
|
|
|
},
|
|
|
|
@ -624,7 +626,7 @@ class ApiClient {
|
|
|
|
|
)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public async createNote(): Promise<NewNoteResponse | null> {
|
|
|
|
|
public async createNote(): Promise<NewNoteResponse | undefined> {
|
|
|
|
|
// NOTE: The initial note version doesn't allow any user input, the first user-made modification
|
|
|
|
|
// is applied through the version creation endpoint
|
|
|
|
|
|
|
|
|
@ -642,7 +644,10 @@ class ApiClient {
|
|
|
|
|
)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public async getActiveFullNote(noteID: string, fetchRemote: boolean): Promise<FullNote | null> {
|
|
|
|
|
public async getActiveFullNote(
|
|
|
|
|
noteID: string,
|
|
|
|
|
fetchRemote: boolean
|
|
|
|
|
): Promise<FullNote | undefined> {
|
|
|
|
|
if (!UUID_REGEX.test(noteID)) {
|
|
|
|
|
throw new Error("Invalid note ID format.")
|
|
|
|
|
}
|
|
|
|
@ -651,6 +656,7 @@ class ApiClient {
|
|
|
|
|
if (!fetchRemote) {
|
|
|
|
|
const cachedNote = this.loadedNotesCache.get(noteID)
|
|
|
|
|
if (cachedNote != null) {
|
|
|
|
|
// console.log(`full note cache hit ${noteID}`)
|
|
|
|
|
this.activeVersion = cachedNote.versionNumber
|
|
|
|
|
return cachedNote
|
|
|
|
|
}
|
|
|
|
@ -669,7 +675,7 @@ class ApiClient {
|
|
|
|
|
})
|
|
|
|
|
const note = this.deserializeFullNote(data)
|
|
|
|
|
|
|
|
|
|
console.log(`[CACHE] Storing ${noteID}`)
|
|
|
|
|
console.log(`caching ${noteID}`)
|
|
|
|
|
this.loadedNotesCache.set(noteID, note)
|
|
|
|
|
this.activeVersion = note.versionNumber
|
|
|
|
|
|
|
|
|
@ -679,7 +685,7 @@ class ApiClient {
|
|
|
|
|
)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public async deleteNote(noteID: string): Promise<void | null> {
|
|
|
|
|
public async deleteNote(noteID: string): Promise<void> {
|
|
|
|
|
if (!UUID_REGEX.test(noteID)) {
|
|
|
|
|
throw new Error("Invalid note ID format.")
|
|
|
|
|
}
|
|
|
|
@ -694,7 +700,7 @@ class ApiClient {
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
if (response.status === 204) {
|
|
|
|
|
console.log("[NOTE] Deletion successful")
|
|
|
|
|
console.log("deletion successful")
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
@ -707,7 +713,7 @@ class ApiClient {
|
|
|
|
|
public async getNoteHistory(
|
|
|
|
|
noteID: string,
|
|
|
|
|
fetchRemote: boolean
|
|
|
|
|
): Promise<VersionMetadata[] | null> {
|
|
|
|
|
): Promise<VersionMetadata[] | undefined> {
|
|
|
|
|
if (!UUID_REGEX.test(noteID)) {
|
|
|
|
|
throw new Error("Invalid note ID format.")
|
|
|
|
|
}
|
|
|
|
@ -715,6 +721,7 @@ class ApiClient {
|
|
|
|
|
if (!fetchRemote) {
|
|
|
|
|
const cachedVersions = this.loadedHistoryCache.get(noteID)
|
|
|
|
|
if (cachedVersions != null) {
|
|
|
|
|
// console.log(`full version cache hit ${noteID}`)
|
|
|
|
|
return cachedVersions
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
@ -732,8 +739,8 @@ class ApiClient {
|
|
|
|
|
})
|
|
|
|
|
const versions = this.deserializeVersionMetadatas(data)
|
|
|
|
|
|
|
|
|
|
console.log(`got ${versions.length} version metadata results, caching ${noteID}`)
|
|
|
|
|
this.loadedHistoryCache.set(noteID, versions)
|
|
|
|
|
console.log(`[VER] Got and cached ${versions.length} version metadata results`)
|
|
|
|
|
|
|
|
|
|
return versions
|
|
|
|
|
},
|
|
|
|
@ -741,7 +748,7 @@ class ApiClient {
|
|
|
|
|
)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public async createVersion(noteID: string, title: string, content: string): Promise<void | null> {
|
|
|
|
|
public async createVersion(noteID: string, title: string, content: string): Promise<void> {
|
|
|
|
|
if (!UUID_REGEX.test(noteID)) {
|
|
|
|
|
throw new Error("Invalid note ID format.")
|
|
|
|
|
}
|
|
|
|
@ -760,7 +767,7 @@ class ApiClient {
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
if (response.status === 204) {
|
|
|
|
|
console.log("[VER] Creation successful")
|
|
|
|
|
console.log("creation successful")
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
@ -770,7 +777,7 @@ class ApiClient {
|
|
|
|
|
)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public async getFullVersion(noteID: string, versionID: string): Promise<FullNote | null> {
|
|
|
|
|
public async getFullVersion(noteID: string, versionID: string): Promise<FullNote | undefined> {
|
|
|
|
|
if (!UUID_REGEX.test(noteID)) {
|
|
|
|
|
throw new Error("Invalid note ID format.")
|
|
|
|
|
}
|
|
|
|
@ -779,13 +786,18 @@ class ApiClient {
|
|
|
|
|
throw new Error("Invalid version ID format.")
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// NOTE: No need to explicitly prevent attempting a cache hit as versions aren't editable
|
|
|
|
|
// NOTE: Versions aren't editable so we don't need to prevent the system from attempting
|
|
|
|
|
// to locate each request's contents first from the cache
|
|
|
|
|
|
|
|
|
|
const cachedVersion = this.loadedVersionsCache.get(noteID + versionID)
|
|
|
|
|
if (cachedVersion != null) {
|
|
|
|
|
// console.log(`full version cache hit [${noteID}, ${versionID}]`)
|
|
|
|
|
return cachedVersion
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// TODO: check if the requested version is the current version -> use `loadedNotesCache`
|
|
|
|
|
// (we probably have to modify the caching mechanism so we can look the regular note items up using versionID)
|
|
|
|
|
|
|
|
|
|
return this.handleRequest(
|
|
|
|
|
async () => {
|
|
|
|
|
const response = await fetch(`${this.baseUrl}/notes/${noteID}/${versionID}`, {
|
|
|
|
@ -800,10 +812,10 @@ class ApiClient {
|
|
|
|
|
const version = this.joinDeserializedVersion(noteID, data)
|
|
|
|
|
|
|
|
|
|
if (!version) {
|
|
|
|
|
return null
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
console.log(`[CACHE] Storing [${noteID}, ${versionID}]`)
|
|
|
|
|
console.log(`caching [${noteID}, ${versionID}]`)
|
|
|
|
|
this.loadedVersionsCache.set(noteID + versionID, version)
|
|
|
|
|
|
|
|
|
|
return version
|
|
|
|
|