/** * appwrite_sdk.js — Production Web SDK for OAuth 2.0 & Account Management * Implements the exact Client and Account SDK contract from the reference video: * - client.setEndpoint(url).setProject(projectId) * - account.createOAuth2Session(provider, successUrl, failureUrl) * - account.get() * - account.listSessions() * - account.deleteSession(sessionId) */ (function (global) { 'use strict'; class Client { constructor() { this.endpoint = window.location.origin + '/v1'; this.project = 'kaveri-oauth-project'; this.headers = { 'Content-Type': 'application/json', 'X-Appwrite-Response-Format': '1.6.0' }; } setEndpoint(endpoint) { this.endpoint = endpoint.replace(/\/+$/, ''); return this; } setProject(project) { this.project = project; this.headers['X-Appwrite-Project'] = project; return this; } async call(method, path, body = null) { const url = this.endpoint + path; const options = { method: method.toUpperCase(), headers: { ...this.headers }, credentials: 'include' }; if (body && (options.method === 'POST' || options.method === 'PUT' || options.method === 'PATCH')) { options.body = JSON.stringify(body); } const res = await fetch(url, options); const data = await res.json().catch(() => ({})); if (!res.ok) { const errMsg = (data.detail && data.detail.message) || data.message || `HTTP Error ${res.status}`; const err = new Error(errMsg); err.code = res.status; err.response = data; throw err; } return data; } } class Account { constructor(client) { if (!(client instanceof Client)) { throw new Error('Account requires a valid Client instance.'); } this.client = client; } /** * Create OAuth2 Session — Redirects browser to the OAuth2 provider flow. * Matches: account.createOAuth2Session('google', successUrl, failureUrl) */ createOAuth2Session(provider, success = '', failure = '') { if (!provider) { throw new Error('OAuth2 provider is required (e.g. "google").'); } const successUrl = success || window.location.href.split('?')[0]; const failureUrl = failure || (window.location.href.split('?')[0] + '?error=oauth_failed'); const params = new URLSearchParams({ project: this.client.project, success: successUrl, failure: failureUrl }); const targetUrl = `${this.client.endpoint}/account/sessions/oauth2/${encodeURIComponent(provider)}?${params.toString()}`; window.location.assign(targetUrl); } /** * Get currently logged-in user account details (`GET /v1/account`). */ async get() { return await this.client.call('GET', '/account'); } /** * List all active sessions for the current user (`GET /v1/account/sessions`). */ async listSessions() { return await this.client.call('GET', '/account/sessions'); } /** * Delete a session (`DELETE /v1/account/sessions/{sessionId}`). * Pass 'current' to log out of the active session. */ async deleteSession(sessionId = 'current') { return await this.client.call('DELETE', `/account/sessions/${encodeURIComponent(sessionId)}`); } /** * Generate RFC 7636 PKCE S256 verifier & challenge pair using Web Crypto API. */ async generatePKCE() { return await generatePKCE(); } /** * Get OAuth2 Provider Console Settings (`GET /v1/account/oauth2/providers/{provider}`). */ async getOAuthProviderSettings(provider = 'google') { return await this.client.call('GET', `/account/oauth2/providers/${encodeURIComponent(provider)}`); } /** * Update OAuth2 Provider Console Settings (`POST /v1/account/oauth2/providers/{provider}`). */ async updateOAuthProviderSettings(provider = 'google', settings = {}) { return await this.client.call('POST', `/account/oauth2/providers/${encodeURIComponent(provider)}`, settings); } } function base64UrlEncode(bytes) { let str = ''; for (let i = 0; i < bytes.length; i++) { str += String.fromCharCode(bytes[i]); } return btoa(str).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''); } async function generatePKCE() { const rand = new Uint8Array(32); if (global.crypto && global.crypto.getRandomValues) { global.crypto.getRandomValues(rand); } else { for (let i = 0; i < rand.length; i++) rand[i] = Math.floor(Math.random() * 256); } const codeVerifier = base64UrlEncode(rand); let codeChallenge = codeVerifier; let codeChallengeMethod = 'plain'; if (global.crypto && global.crypto.subtle && global.TextEncoder) { const digest = await global.crypto.subtle.digest('SHA-256', new TextEncoder().encode(codeVerifier)); codeChallenge = base64UrlEncode(new Uint8Array(digest)); codeChallengeMethod = 'S256'; } try { sessionStorage.setItem('kaveri_oauth_pkce_verifier', codeVerifier); } catch (_) {} return { codeVerifier, codeChallenge, codeChallengeMethod }; } global.Appwrite = { Client: Client, Account: Account, generatePKCE: generatePKCE }; })(window);