### Claim Reward Balance Operation Example Source: https://github.com/ecency/hivesigner-api/blob/main/_autodocs/QUICK_REFERENCE.md Example of the parameters for a 'claim_reward_balance' operation. ```json {account: "alice", reward_hive: "1.000", ...} ``` -------------------------------- ### Example Token Object Source: https://github.com/ecency/hivesigner-api/blob/main/_autodocs/types.md An example of a decoded authentication token. This specific example shows a 'posting' type token issued by 'hiveapp' for user 'alice'. ```javascript { "signed_message": { "type": "posting", "app": "hiveapp" }, "authors": ["alice"], "signatures": ["20551...truncated"], "timestamp": 1692345678 } ``` -------------------------------- ### Start Hivesigner Broadcast Server Source: https://github.com/ecency/hivesigner-api/blob/main/_autodocs/00_START_HERE.md Run this command to start the Hivesigner broadcast server. The server will listen on the port specified by API_PORT. ```bash npm start # Listening on port 3000 ``` -------------------------------- ### Account Update2 Operation Example Source: https://github.com/ecency/hivesigner-api/blob/main/_autodocs/QUICK_REFERENCE.md Example of the parameters for an 'account_update2' operation. ```json {account: "alice", memo_key: "STM..."} ``` -------------------------------- ### App Profile Object Example Source: https://github.com/ecency/hivesigner-api/blob/main/_autodocs/types.md An example of an AppProfile object, showing configuration for an application with a secret and allowed IP addresses. ```javascript { "profile": { "type": "app", "secret": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "allowed_ips": ["203.0.113.0/24", "198.51.100.50"] } } ``` -------------------------------- ### Comment Options Operation Example Source: https://github.com/ecency/hivesigner-api/blob/main/_autodocs/QUICK_REFERENCE.md Example of the parameters for a 'comment_options' operation. ```json {author: "alice", permlink: "id", ...} ``` -------------------------------- ### Comment Operation Example Source: https://github.com/ecency/hivesigner-api/blob/main/_autodocs/QUICK_REFERENCE.md Example of the parameters for a 'comment' operation. ```json {author: "alice", body: "text", permlink: "id"} ``` -------------------------------- ### Authorization Chain Example Source: https://github.com/ecency/hivesigner-api/blob/main/_autodocs/README.md Illustrates the permission chain required for transaction broadcasting, from user to broadcaster. ```text User grants posting permission to Proxy App ↓ Proxy App grants posting permission to Broadcaster ↓ Broadcaster signs and broadcasts transaction ``` -------------------------------- ### Import and Get Account from Client Module Source: https://github.com/ecency/hivesigner-api/blob/main/_autodocs/api-reference/EXPORTS.md Demonstrates importing `getAccount` from the client module to query user account information. ```javascript import { client, bclient, getAccount } from './helpers/client.js'; // Query account const accounts = await getAccount('alice'); ``` -------------------------------- ### Vote Operation Example Source: https://github.com/ecency/hivesigner-api/blob/main/_autodocs/QUICK_REFERENCE.md Example of the parameters for a 'vote' operation. ```json {voter: "alice", author: "bob", permlink: "post"} ``` -------------------------------- ### Custom JSON Operation Example Source: https://github.com/ecency/hivesigner-api/blob/main/_autodocs/QUICK_REFERENCE.md Example of the parameters for a 'custom_json' operation, requiring posting authorization. ```json {required_posting_auths: ["alice"], id: "app"} ``` -------------------------------- ### Authority Object Example Source: https://github.com/ecency/hivesigner-api/blob/main/_autodocs/types.md An example of an Authority object, illustrating how public keys and accounts are authorized with specific weights. ```javascript { "weight_threshold": 1, "key_auths": [ ["STM7pQVQSzpLnJnMyQ5j5gLUw3sHv5B51M...", 1] ], "account_auths": [ ["myapp", 1], ["hivesigner", 1] ] } ``` -------------------------------- ### Example Token Decoding Source: https://github.com/ecency/hivesigner-api/blob/main/_autodocs/api-reference/token.md Demonstrates how to decode a Base64URL encoded token string into a JavaScript object using a helper function and then parse it as JSON. Shows how to access specific fields like the author's username. ```javascript import { b64uDec } from './helpers/utils.js'; const token = "eyJzaWduZWRfbWVzc2FnZSI..."; const decoded = b64uDec(token); // Convert to JSON const tokenObj = JSON.parse(decoded); console.log(tokenObj.authors[0]); // "alice" ``` -------------------------------- ### Hivesigner API Configuration File Source: https://github.com/ecency/hivesigner-api/blob/main/_autodocs/README.md Example JSON configuration file for Hivesigner API, specifying token expiration and authorized operations. ```json { "token_expiration": 604800, "authorized_operations": [ "vote", "comment", "delete_comment", "comment_options", "custom_json", "claim_reward_balance", "account_update2" ] } ``` -------------------------------- ### API Router Export Source: https://github.com/ecency/hivesigner-api/blob/main/_autodocs/api-reference/routes.md This snippet shows how the API router is exported and imported in the application's start file. ```javascript import apis from './routes/api.js'; app.use('/api', apis); ``` -------------------------------- ### Get Account and Scope Source: https://github.com/ecency/hivesigner-api/blob/main/_autodocs/api-reference/routes.md Retrieves the authenticated account's information and associated scopes. ```APIDOC ## GET/POST /me ### Description Get the current account and its scopes. ### Method GET/POST ### Endpoint /me ``` -------------------------------- ### Example: Unauthorized Client Error (Missing Proxy Permission) Source: https://github.com/ecency/hivesigner-api/blob/main/_autodocs/errors.md This JSON object represents an 'unauthorized_client' error, indicating that an app lacks permission to broadcast for a specific user. ```json { "error": "unauthorized_client", "error_description": "The app @myapp doesn't have permission to broadcast for @alice" } ``` -------------------------------- ### Get User Account Information Source: https://github.com/ecency/hivesigner-api/blob/main/_autodocs/QUICK_REFERENCE.md Fetches user details, scope, and account information using an access token in the Authorization header. ```javascript const res = await fetch('/api/me', { headers: { 'Authorization': `Bearer ${token}` } }); const { user, scope, account } = await res.json(); ``` -------------------------------- ### Get Account Data Source: https://github.com/ecency/hivesigner-api/blob/main/_autodocs/api-reference/EXPORTS.md Queries account data with optional caching. Caching has a 120-second TTL if enabled. ```javascript export const getAccount = async ( user: string, isCached?: boolean ): Promise => { // Implementation details... return undefined; }; ``` -------------------------------- ### Import and Use Cache Module for Retrieving Data Source: https://github.com/ecency/hivesigner-api/blob/main/_autodocs/api-reference/EXPORTS.md Shows importing the `cache` object from the cache module and using its `get` method to retrieve previously stored data. ```javascript import { cache } from './helpers/cache.js'; // Retrieve const value = cache.get('key'); ``` -------------------------------- ### GET/POST /me Source: https://github.com/ecency/hivesigner-api/blob/main/_autodocs/api-reference/EXPORTS.md Authenticates the user and retrieves account information. This endpoint can be accessed using either GET or POST methods. ```APIDOC ## GET/POST /me ### Description Authenticates the user and retrieves account information. ### Method GET, POST ### Endpoint /me ### Parameters #### Query Parameters - **username** (string) - Required - The username of the account to authenticate. - **key** (string) - Required - The public key associated with the account. ### Response #### Success Response (200) - **account** (object) - The authenticated user's account details. - **token** (string) - A JWT token for subsequent authenticated requests. ``` -------------------------------- ### Express Route with verifyPermissions Middleware Source: https://github.com/ecency/hivesigner-api/blob/main/_autodocs/api-reference/middleware.md This example demonstrates how to integrate the verifyPermissions middleware into an Express.js route. It ensures that only authenticated users with proper proxy and broadcaster permissions can access the broadcast endpoint. ```javascript import { Router } from 'express'; import { authenticate, verifyPermissions } from './helpers/middleware.js'; const router = Router(); router.post('/api/broadcast', authenticate('app'), verifyPermissions, (req, res) => { // Only reached if: // 1. Token is valid app-type token // 2. User account exists and authorized proxy to post on their behalf // 3. Proxy account exists and authorized broadcaster to post on their behalf res.json({ success: true }); } ); ``` -------------------------------- ### Environment Variables for Hivesigner Broadcast Source: https://github.com/ecency/hivesigner-api/blob/main/_autodocs/00_START_HERE.md Set these environment variables before starting the Hivesigner broadcast server. Ensure you have the correct WIF and network specified. ```bash BROADCASTER_USERNAME=hivesigner_broadcast BROADCASTER_POSTING_WIF=5JrphYr... BROADCAST_NETWORK=mainnet API_PORT=3000 ``` -------------------------------- ### authenticate() Middleware Examples Source: https://github.com/ecency/hivesigner-api/blob/main/_autodocs/api-reference/middleware.md Demonstrates various ways to use the authenticate() middleware for different access control scenarios in an Express.js application. This includes allowing any authenticated user, restricting access to 'app' tokens, and permitting 'code' or 'refresh' tokens. ```javascript import { Router } from 'express'; import { authenticate } from './helpers/middleware.js'; const router = Router(); // Any authenticated user router.get('/api/me', authenticate(), (req, res) => { res.json({ user: req.user }); }); // Only app-type tokens router.post('/api/broadcast', authenticate('app'), (req, res) => { // Process broadcast }); // Only code or refresh tokens router.post('/api/oauth2/token', authenticate(['code', 'refresh']), (req, res) => { // Issue new tokens }); ``` -------------------------------- ### GET/POST /decode Source: https://github.com/ecency/hivesigner-api/blob/main/_autodocs/api-reference/EXPORTS.md Decodes a memo using the provided key. This endpoint supports both GET and POST methods. ```APIDOC ## GET/POST /decode ### Description Decodes a memo using the provided key. ### Method GET, POST ### Endpoint /decode ### Parameters #### Query Parameters - **memo** (string) - Required - The memo to decode. - **key** (string) - Required - The private key to use for decoding. ### Response #### Success Response (200) - **decodedMemo** (string) - The decoded memo content. ``` -------------------------------- ### Example Error Response Source: https://github.com/ecency/hivesigner-api/blob/main/_autodocs/QUICK_REFERENCE.md Illustrates a typical error response from the API, indicating an unauthorized operation due to insufficient scope. ```json { "error": "invalid_scope", "error_description": "The access_token scope does not allow the following operation(s): custom_json" } ``` -------------------------------- ### GET/POST /me - Server Error Response Source: https://github.com/ecency/hivesigner-api/blob/main/_autodocs/api-reference/routes.md Example of a server error response when the hived API fails during account fetching. ```json { error: "server_error", error_description: "Request to hived API failed" } ``` -------------------------------- ### Scope and Permissions Example Source: https://github.com/ecency/hivesigner-api/blob/main/_autodocs/README.md Defines the array of authorized Hive operations for a token's scope. Broadcasting operations outside this scope will result in an 'invalid_scope' error. ```javascript ["vote", "comment", "custom_json", "claim_reward_balance"] ``` -------------------------------- ### Example: Unauthorized Access Error Response Source: https://github.com/ecency/hivesigner-api/blob/main/_autodocs/errors.md This JSON object demonstrates an 'unauthorized_access' error, returned when a request originates from an IP address not listed in the app's allowed IPs. ```json { "error": "unauthorized_access", "error_description": "The IP 203.0.113.5 is not authorized" } ``` -------------------------------- ### Docker Build and Run Commands Source: https://github.com/ecency/hivesigner-api/blob/main/_autodocs/configuration.md Build a Docker image for the Hivesigner API and run it as a container. Ensure to set the necessary environment variables for the broadcaster. ```bash docker build -t hivesigner-api . docker run -e BROADCASTER_USERNAME=... -e BROADCASTER_POSTING_WIF=... -p 3000:3000 hivesigner-api ``` -------------------------------- ### Get Account with Cache Integration Source: https://github.com/ecency/hivesigner-api/blob/main/_autodocs/api-reference/cache.md Fetches account data, utilizing the cache. If cached data is available and valid, it's returned directly. Otherwise, it fetches fresh data from the blockchain and caches it for future use with a 120-second TTL. This method optimizes data retrieval by minimizing blockchain lookups. ```javascript import { cache } from './helpers/cache.js'; export const getAccount = async (user, isCached = true) => { // Check cache first let account = isCached ? cache.get(`${user}`) : undefined; if (account === undefined) { // Cache miss - fetch from blockchain account = await client.database.getAccounts([user]); // Cache with 120-second TTL cache.set(`${user}`, account, 120); } return account; }; ``` -------------------------------- ### Import and Use Client Directly from Client Module Source: https://github.com/ecency/hivesigner-api/blob/main/_autodocs/api-reference/EXPORTS.md Shows how to import the `client` object from the client module and use its `database.getAccounts` method to retrieve account details. ```javascript import { client, bclient, getAccount } from './helpers/client.js'; // Use client directly const accounts2 = await client.database.getAccounts(['bob']); ``` -------------------------------- ### Import and Broadcast Operations using Client Module Source: https://github.com/ecency/hivesigner-api/blob/main/_autodocs/api-reference/EXPORTS.md Illustrates importing `bclient` from the client module and using its `broadcast.sendOperations` method to broadcast operations with a private key. ```javascript import { client, bclient, getAccount } from './helpers/client.js'; // Broadcast await bclient.broadcast.sendOperations(operations, privateKey); ``` -------------------------------- ### Delete Comment Operation Example Source: https://github.com/ecency/hivesigner-api/blob/main/_autodocs/QUICK_REFERENCE.md Example of the parameters for a 'delete_comment' operation. ```json {author: "alice", permlink: "id"} ``` -------------------------------- ### Import and Verify Token from Token Module Source: https://github.com/ecency/hivesigner-api/blob/main/_autodocs/api-reference/EXPORTS.md Illustrates importing the `verify` function from the token module to check the validity of a token against a message, user, and signature. ```javascript import { decodeMemo, issue, verify } from './helpers/token.js'; // Verify token verify(message, 'alice', signature, (err, valid) => { console.log(valid); }); ``` -------------------------------- ### Build and Run Hivesigner API with Docker Source: https://github.com/ecency/hivesigner-api/blob/main/_autodocs/README.md Builds the Docker image for the Hivesigner API and runs it as a container. Ensure environment variables like BROADCASTER_USERNAME and BROADCASTER_POSTING_WIF are set correctly for your deployment. ```bash docker build -t hivesigner-api . docker run \ -e BROADCASTER_USERNAME=hivesigner \ -e BROADCASTER_POSTING_WIF='5J...' \ -e BROADCAST_NETWORK=mainnet \ -e API_PORT=3000 \ -p 3000:3000 \ hivesigner-api ``` -------------------------------- ### Get Account Details Source: https://github.com/ecency/hivesigner-api/blob/main/_autodocs/endpoints.md Retrieves authenticated user's account information, including Hive account data, profile metadata, and authorized scopes. Supports both GET and POST methods. ```APIDOC ## GET/POST /api/me ### Description Retrieve authenticated user's account information including Hive account data, profile metadata, and authorized scopes. ### Method GET/POST ### Endpoint /api/me ### Parameters #### Query Parameters - **access_token** (string) - Required - Authentication token (can also be passed via header or body). #### Request Body - **access_token** (string) - Required - Authentication token (can also be passed via header or query parameter). ### Request Example ```javascript fetch('/api/me', { method: 'GET', // or 'POST' headers: { 'Authorization': 'Bearer YOUR_ACCESS_TOKEN' } }) .then(response => response.json()) .then(data => console.log(data)); ``` ### Response #### Success Response (200) - **user** (string) - Username of authenticated account. - **_id** (string) - Same as user (account identifier). - **name** (string) - Same as user (account name). - **account** (object) - Full Hive account object including balance, resource credits, account history. - **scope** (array) - List of authorized operations the token permits (e.g., `["vote", "comment"]`). - **user_metadata** (object) - Parsed profile metadata from account's `posting_json_metadata` or `json_metadata`. #### Response Example { "user": "alice", "_id": "alice", "name": "alice", "account": { "name": "alice", "balance": "100.000 HIVE", "vesting_shares": "2000000.000000 VESTS", "delegated_vesting_shares": "0.000000 VESTS", "received_vesting_share_bandwidth": "0.000000 VESTS", "voting_power": 10000, "last_vote_time": "2023-10-27T10:00:00", "proxy": "", "next_vesting_withdrawal": "1970-01-01T00:00:00", "withdrawn": 0, "to_withdraw": 0, "withdraw_rate": "0.000000 VESTS", "last_account_update": "2023-10-26T12:00:00", "created": "2020-01-01T00:00:00", "min_voting_power": 0, "max_conjugated_actions": 0 }, "scope": ["vote", "comment", "custom_json"], "user_metadata": { "profile": { "name": "Alice", "about": "A Hive user.", "profile_image": "https://example.com/image.png", "cover_image": "https://example.com/cover.png" } } } ``` -------------------------------- ### Import and Decode Memo from Token Module Source: https://github.com/ecency/hivesigner-api/blob/main/_autodocs/api-reference/EXPORTS.md Demonstrates how to import the `decodeMemo` function from the token module and use it to decode an encrypted memo. ```javascript import { decodeMemo, issue, verify } from './helpers/token.js'; // Decode memo const decoded = await decodeMemo(encrypted); ``` -------------------------------- ### GET /_health Source: https://github.com/ecency/hivesigner-api/blob/main/_autodocs/QUICK_REFERENCE.md Checks the health status of the API. ```APIDOC ## GET /_health ### Description Checks the health status of the API. ### Method GET ### Endpoint /_health ### Response #### Success Response (200) - **ok** (boolean) - Indicates if the API is healthy. ### Response Example ```json { "ok": true } ``` ``` -------------------------------- ### Environment Variables for Broadcaster Source: https://github.com/ecency/hivesigner-api/blob/main/_autodocs/QUICK_REFERENCE.md Sets up required and optional environment variables for the broadcaster service. Ensure BROADCASTER_USERNAME and BROADCASTER_POSTING_WIF are defined. ```bash # Required BROADCASTER_USERNAME=hivesigner_broadcast BROADCASTER_POSTING_WIF=5JrphYr... # Optional (defaults shown) BROADCAST_NETWORK=mainnet # or 'testnet' API_PORT=3000 ``` -------------------------------- ### Hivesigner Token Structure Source: https://github.com/ecency/hivesigner-api/blob/main/_autodocs/QUICK_REFERENCE.md Example of the structure for a Base64URL-encoded JSON token used by Hivesigner. ```javascript { signed_message: { type: "posting|refresh|code|login|offline", app: "appname" }, authors: ["username"], signatures: ["signature_string"], timestamp: 1692345678 } ``` -------------------------------- ### Error Response: Invalid Grant Source: https://github.com/ecency/hivesigner-api/blob/main/_autodocs/api-reference/routes.md Example of an error response when the provided code or secret is invalid. ```json { error: "invalid_grant", error_description": "The code or secret is not valid" } ``` -------------------------------- ### Initialize Express Router Source: https://github.com/ecency/hivesigner-api/blob/main/_autodocs/api-reference/routes.md Sets up the Express Router for defining API endpoints. This is the entry point for all API route definitions. ```javascript import { Router } from 'express'; const router = Router(); export default router; ``` -------------------------------- ### GET/POST /oauth2/token/revoke Source: https://github.com/ecency/hivesigner-api/blob/main/_autodocs/api-reference/EXPORTS.md Revokes an OAuth2 access token. This endpoint can be accessed using GET or POST. ```APIDOC ## GET/POST /oauth2/token/revoke ### Description Revokes an OAuth2 access token. ### Method GET, POST ### Endpoint /oauth2/token/revoke ### Parameters #### Query Parameters - **token** (string) - Required - The access token to revoke. - **client_id** (string) - Required - The client ID of the application. ### Response #### Success Response (200) - **message** (string) - A confirmation message indicating the token has been revoked. ``` -------------------------------- ### Import and Use Cache Module for Storing Data Source: https://github.com/ecency/hivesigner-api/blob/main/_autodocs/api-reference/EXPORTS.md Demonstrates importing the `cache` object from the cache module and using its `set` method to store data with a Time-To-Live (TTL). ```javascript import { cache } from './helpers/cache.js'; // Store cache.set('key', { data: 'value' }, 120); ``` -------------------------------- ### Import API Routes and Mount to Express App Source: https://github.com/ecency/hivesigner-api/blob/main/_autodocs/api-reference/EXPORTS.md Demonstrates importing the `apis` router from the routes/api.js file and mounting it onto the Express application at the '/api' path. ```javascript import apis from './routes/api.js'; app.use('/api', apis); ``` -------------------------------- ### Get Authenticated User Source: https://github.com/ecency/hivesigner-api/blob/main/_autodocs/README.md Retrieves the authenticated user's account details and authorized scopes. ```APIDOC ## GET/POST /api/me ### Description Get authenticated user's account and scopes. ### Method GET, POST ### Endpoint /api/me ### Parameters ### Request Example ```json { "example": "request body" } ``` ### Response #### Success Response (200) - **field1** (type) - Description #### Response Example ```json { "example": "response body" } ``` ``` -------------------------------- ### Import Utility Functions for Encoding/Decoding Source: https://github.com/ecency/hivesigner-api/blob/main/_autodocs/api-reference/EXPORTS.md Shows importing `b64uEnc` and `b64uDec` from the utils module for Base64 URL-safe encoding and decoding. ```javascript import { getErrorMessage, isOperationAuthor, getAppProfile, b64uEnc, b64uDec } from './helpers/utils.js'; // Encode/decode const encoded = b64uEnc('{"type":"posting"}'); const decoded = b64uDec(encoded); ``` -------------------------------- ### Error Response: Invalid Token Role Source: https://github.com/ecency/hivesigner-api/blob/main/_autodocs/api-reference/routes.md Example of an error response when the provided token has an invalid role. ```json { error: "invalid_grant", error_description": "The token has invalid role" } ``` -------------------------------- ### Import and Issue Token from Token Module Source: https://github.com/ecency/hivesigner-api/blob/main/_autodocs/api-reference/EXPORTS.md Shows how to import the `issue` function from the token module to create a new token for a specific application and user. ```javascript import { decodeMemo, issue, verify } from './helpers/token.js'; // Issue token const token = issue('myapp', 'alice', 'posting'); ``` -------------------------------- ### Error Response: Unauthorized Access Source: https://github.com/ecency/hivesigner-api/blob/main/_autodocs/api-reference/routes.md Example of an error response when the client's IP address is not authorized. ```json { error: "unauthorized_access", error_description": "The IP 203.0.113.5 is not authorized" } ``` -------------------------------- ### GET/POST /me - Invalid Token Response Source: https://github.com/ecency/hivesigner-api/blob/main/_autodocs/api-reference/routes.md Example of an invalid token response when the token has an invalid role. ```json { error: "invalid_grant", error_description: "The token has invalid role" } ``` -------------------------------- ### Configuration File Structure Source: https://github.com/ecency/hivesigner-api/blob/main/_autodocs/configuration.md The `config.json` file defines global settings for the API, such as token expiration duration and the list of operations permitted within a broadcast scope. ```json { "token_expiration": 604800, "authorized_operations": [ "vote", "comment", "delete_comment", "comment_options", "custom_json", "claim_reward_balance", "account_update2" ] } ``` -------------------------------- ### Import Middleware Strategy Source: https://github.com/ecency/hivesigner-api/blob/main/_autodocs/api-reference/EXPORTS.md Demonstrates importing the `strategy` from the middleware module and applying it to the Express app. ```javascript import { strategy, authenticate, verifyPermissions } from './helpers/middleware.js'; // Apply to app app.use(strategy); ``` -------------------------------- ### Enable Detailed Logging for API Source: https://github.com/ecency/hivesigner-api/blob/main/_autodocs/errors.md Run the API with specific environment variables to enable detailed logging to stdout. This helps in tracking validation and broadcast attempts. ```bash API_PORT=3000 BROADCASTER_USERNAME=... BROADCASTER_POSTING_WIF=... node start.js ``` -------------------------------- ### Get Account Information Source: https://github.com/ecency/hivesigner-api/blob/main/_autodocs/QUICK_REFERENCE.md Retrieve information about the authenticated user. Requires a Bearer token in the Authorization header. ```http GET/POST /api/me Authorization: Bearer ``` -------------------------------- ### Required Environment Variables for Hivesigner API Source: https://github.com/ecency/hivesigner-api/blob/main/_autodocs/README.md Lists the essential environment variables needed to configure the Hivesigner API, including broadcaster credentials and network settings. ```bash # Broadcaster account (signs all transactions) BROADCASTER_USERNAME=hivesigner_broadcast BROADCASTER_POSTING_WIF=5JrphYr... # Network target BROADCAST_NETWORK=mainnet # or 'testnet' # Server port API_PORT=3000 ``` -------------------------------- ### Get User Account Source: https://github.com/ecency/hivesigner-api/blob/main/_autodocs/QUICK_REFERENCE.md Retrieves information about the authenticated user, including their username, granted scope, and account details. ```APIDOC ## GET /api/me ### Description Retrieves the authenticated user's profile information and granted permissions. ### Method GET ### Endpoint /api/me ### Parameters #### Query Parameters - **access_token** (string) - Required - The access token for authentication. #### Request Example ```javascript fetch('/api/me?access_token=' + token) ``` ### Response #### Success Response (200) - **user** (string) - The username of the authenticated user. - **scope** (string) - The scope of permissions granted by the token. - **account** (object) - Detailed account information. #### Response Example ```json { "user": "alice", "scope": "login,vote", "account": { ... } } ``` ``` -------------------------------- ### Import Middleware for Route Authentication and Permissions Source: https://github.com/ecency/hivesigner-api/blob/main/_autodocs/api-reference/EXPORTS.md Shows importing `authenticate` and `verifyPermissions` from the middleware module for use in securing API routes. ```javascript import { strategy, authenticate, verifyPermissions } from './helpers/middleware.js'; // Use in routes router.post('/broadcast', authenticate('app'), verifyPermissions, handler ); ``` -------------------------------- ### Import Utility Function for App Profile Source: https://github.com/ecency/hivesigner-api/blob/main/_autodocs/api-reference/EXPORTS.md Illustrates importing `getAppProfile` from the utils module to retrieve application profile information. ```javascript import { getErrorMessage, isOperationAuthor, getAppProfile, b64uEnc, b64uDec } from './helpers/utils.js'; // Get app info const profile = await getAppProfile('myapp'); ``` -------------------------------- ### Error Response for Unauthorized Client Source: https://github.com/ecency/hivesigner-api/blob/main/_autodocs/endpoints.md Example of an error response when the access token is associated with a client that is not authorized for the requested action. ```json { "error": "unauthorized_client", "error_description": "This access_token allow you to broadcast transaction only for the account @alice" } ``` -------------------------------- ### Authenticate with Token in Query Parameter Source: https://github.com/ecency/hivesigner-api/blob/main/_autodocs/QUICK_REFERENCE.md Shows how to pass an access token as a query parameter in a fetch request. ```javascript fetch('/api/me?access_token=' + token) ``` -------------------------------- ### Token Expiration Time Source: https://github.com/ecency/hivesigner-api/blob/main/_autodocs/types.md Defines the duration for which a token remains valid, specified in seconds. This example sets the expiration to 7 days. ```javascript const token_expiration = 604800 // 7 days in seconds ``` -------------------------------- ### GET/POST /oauth2/token Source: https://github.com/ecency/hivesigner-api/blob/main/_autodocs/api-reference/EXPORTS.md Obtains an OAuth2 access token. Supports 'code' and 'refresh' grant types. Accessible via GET or POST. ```APIDOC ## GET/POST /oauth2/token ### Description Obtains an OAuth2 access token. ### Method GET, POST ### Endpoint /oauth2/token ### Parameters #### Query Parameters - **grant_type** (string) - Required - The grant type, either 'code' or 'refresh'. - **code** (string) - Required if grant_type is 'code' - The authorization code received from the authorization server. - **refresh_token** (string) - Required if grant_type is 'refresh' - The refresh token. - **client_id** (string) - Required - The client ID of the application. ### Response #### Success Response (200) - **access_token** (string) - The OAuth2 access token. - **expires_in** (integer) - The lifetime in seconds of the access token. - **refresh_token** (string) - The refresh token (if grant_type was 'code'). ``` -------------------------------- ### Example: Invalid Grant Error Response Source: https://github.com/ecency/hivesigner-api/blob/main/_autodocs/errors.md This JSON object represents an 'invalid_grant' error, typically returned when a token is invalid or has an incorrect role. ```json { "error": "invalid_grant", "error_description": "The token has invalid role" } ``` -------------------------------- ### Read Client Configuration (Testnet) Source: https://github.com/ecency/hivesigner-api/blob/main/_autodocs/configuration.md Configuration for the read-only Hive client used for querying account data and verifying permissions on the testnet. ```javascript { servers: ['https://testnet.openhive.network'], timeout: 4000, failoverThreshold: 4, consoleOnFailover: true, addressPrefix: 'TST', chainId: '18dcf0a285365fc58b71f18b3d3fec954aa0c141c44e4e5cb4cf777b9eab274e' } ``` -------------------------------- ### Check App Profile Structure Source: https://github.com/ecency/hivesigner-api/blob/main/_autodocs/errors.md Retrieve and log an application's profile using the `getAppProfile` helper function. Ensure the app is registered and has the correct profile structure. ```javascript import { getAppProfile } from './helpers/utils.js'; const profile = await getAppProfile('myapp') .then(p => console.log(JSON.stringify(p, null, 2))) .catch(e => console.error('App not registered:', e)); ``` -------------------------------- ### Example: Invalid Scope Error Response Source: https://github.com/ecency/hivesigner-api/blob/main/_autodocs/errors.md This JSON object illustrates an 'invalid_scope' error, indicating that the token's scope does not permit the requested operations. ```json { "error": "invalid_scope", "error_description": "The access_token scope does not allow the following operation(s): custom_json, vote" } ``` -------------------------------- ### NodeCache Configuration Source: https://github.com/ecency/hivesigner-api/blob/main/_autodocs/configuration.md Configure default Time-To-Live (TTL) and the interval for checking expired keys in the NodeCache. Default TTL is disabled. ```javascript { stdTTL: 0, // Default TTL disabled checkperiod: 120 // Check for expired keys every 120 seconds } ``` -------------------------------- ### Core Modules Overview Source: https://github.com/ecency/hivesigner-api/blob/main/_autodocs/INDEX.md This section details the core modules available within the HiveSigner API, including their respective file paths, word counts, and a brief description of their contents. It covers route handlers, middleware, token utilities, blockchain clients, general utilities, caching mechanisms, and export details. ```APIDOC ## Core Modules Overview This section details the core modules available within the HiveSigner API, including their respective file paths, word counts, and a brief description of their contents. It covers route handlers, middleware, token utilities, blockchain clients, general utilities, caching mechanisms, and export details. ### Module List: 1. **[api-reference/routes.md](api-reference/routes.md)** - Express route handlers for all endpoints - Middleware chain documentation - Request/response for each route - Validation rules and logging 2. **[api-reference/middleware.md](api-reference/middleware.md)** - `strategy()` — Token extraction and validation - `authenticate()` — Role-based authentication middleware - `verifyPermissions()` — Permission chain verification - Authorization setup examples 3. **[api-reference/token.md](api-reference/token.md)** - `decodeMemo()` — Decrypt encrypted memos - `issue()` — Generate signed tokens - `verify()` — Validate token signatures - Token format and encoding details 4. **[api-reference/client.md](api-reference/client.md)** - `client` — Read-only blockchain client - `bclient` — Broadcast-optimized client - `getAccount()` — Query and cache account data - Network configuration (mainnet/testnet) 5. **[api-reference/utils.md](api-reference/utils.md)** - `getErrorMessage()` — Parse blockchain errors - `isOperationAuthor()` — Validate operation authorship - `getAppProfile()` — Retrieve app metadata - Base64URL encoding/decoding functions - Operation author map reference 6. **[api-reference/cache.md](api-reference/cache.md)** - `cache` — In-memory caching system - Cache configuration and usage - Account data caching strategy - Performance and limitations 7. **[api-reference/EXPORTS.md](api-reference/EXPORTS.md)** - Complete list of exported functions and objects - Function signatures and parameters - Import examples - Function call graph - Constants and environment variables ``` -------------------------------- ### Initialize Broadcast-Optimized Hive Client Source: https://github.com/ecency/hivesigner-api/blob/main/_autodocs/api-reference/client.md Initializes a broadcast-optimized dhive Client instance for submitting transactions. This client has a shorter timeout and more aggressive failover for write operations. ```javascript import { bclient } from './helpers/client.js'; // Broadcast transaction const operations = [['vote', { ... }]]; const privateKey = PrivateKey.fromString(wif); await bclient.broadcast.sendOperations(operations, privateKey); ``` -------------------------------- ### Exchange Authorization Code for Access Token Source: https://github.com/ecency/hivesigner-api/blob/main/_autodocs/00_START_HERE.md Use this JavaScript snippet to exchange an authorization code obtained from a callback with your application's secret to get an access token. ```javascript const response = await fetch('/api/oauth2/token', { method: 'POST', body: JSON.stringify({ code: codeFromCallback, client_secret: appSecret }) }); const { access_token } = await response.json(); ``` -------------------------------- ### API Error: Missing Authorization Source: https://github.com/ecency/hivesigner-api/blob/main/_autodocs/errors.md Example of an HTTP 401 Unauthorized response due to missing or invalid authorization token. This typically occurs when a request lacks the necessary credentials. ```http POST /api/me HTTP/1.1 Host: api.hivesigner.com HTTP/1.1 401 Unauthorized Content-Type: application/json { "error": "invalid_grant", "error_description": "The token has invalid role" } ``` -------------------------------- ### Hivesigner API Project File Structure Source: https://github.com/ecency/hivesigner-api/blob/main/_autodocs/00_START_HERE.md Overview of the directory structure for the Hivesigner API project. This helps in navigating and understanding the project's organization. ```text output/ ├── 00_START_HERE.md .................. This file ├── QUICK_REFERENCE.md ............... Essential reference ├── README.md ........................ Overview & guide ├── INDEX.md ......................... Complete index ├── endpoints.md ..................... HTTP API ├── configuration.md ................. Setup ├── types.md ......................... Types ├── errors.md ........................ Errors └── api-reference/ ├── EXPORTS.md ................... All exports ├── routes.md .................... Route handlers ├── middleware.md ................ Auth middleware ├── token.md ..................... Token module ├── client.md .................... Client module ├── utils.md ..................... Utils module └── cache.md ..................... Cache module ``` -------------------------------- ### Read Client Configuration (Mainnet) Source: https://github.com/ecency/hivesigner-api/blob/main/_autodocs/configuration.md Configuration for the read-only Hive client used for querying account data and verifying permissions on the mainnet. ```javascript { servers: ['https://api.hive.blog', 'https://techcoderx.com', 'https://api.deathwing.me'], timeout: 4000, failoverThreshold: 4, consoleOnFailover: true, addressPrefix: 'STM', chainId: 'beeab0de00000000000000000000000000000000000000000000000000000000' } ``` -------------------------------- ### Handling 401 Unauthorized with Invalid Scope Source: https://github.com/ecency/hivesigner-api/blob/main/_autodocs/errors.md Catch 'invalid_scope' errors when the token's scope does not permit the requested operation. This example demonstrates checking the error status and code. ```javascript const res = await fetch('/api/broadcast', { method: 'POST', body: JSON.stringify({ operations: [...], access_token: token }) }); if (res.status === 401) { const err = await res.json(); if (err.error === 'invalid_scope') { console.error('Token lacks required scope:', err.error_description); } } ``` -------------------------------- ### API Error: Blockchain Failure Source: https://github.com/ecency/hivesigner-api/blob/main/_autodocs/errors.md Example of an HTTP 501 Service Unavailable response due to a failure in the underlying blockchain operation, such as insufficient bandwidth. The response includes details about the blockchain error. ```http POST /api/broadcast HTTP/1.1 Authorization: Bearer eyJ... Content-Type: application/json {"operations":[["vote",{...}]]} HTTP/1.1 501 Service Unavailable Content-Type: application/json { "error": "server_error", "error_description": "Account alice does not have enough bandwidth", "response": { "data": { "stack": [{ "format": "Account ${account} does not have enough ${resource}", "data": {"account":"alice","resource":"bandwidth"} }] } } } ``` -------------------------------- ### Environment Variables for Broadcaster Source: https://github.com/ecency/hivesigner-api/blob/main/_autodocs/api-reference/EXPORTS.md Specifies environment variables required for broadcaster configuration, including username, private key, network, and API port. Ensure these are set before running the broadcaster. ```javascript process.env.BROADCASTER_USERNAME process.env.BROADCASTER_POSTING_WIF process.env.BROADCAST_NETWORK process.env.API_PORT ``` -------------------------------- ### verifyPermissions() Source: https://github.com/ecency/hivesigner-api/blob/main/_autodocs/api-reference/EXPORTS.md Middleware to verify the posting authority chain, ensuring the user, app, and broadcaster are correctly linked. It calls `next()` on success or responds with a 401 error if permissions are invalid. Requires `req.user` and `req.proxy` to be set by `authenticate()`. ```APIDOC ## verifyPermissions() ### Description Verify posting authority chain (user → app → broadcaster). ### Signature ```javascript export const verifyPermissions = async ( req: express.Request, res: express.Response, next: express.NextFunction ): Promise ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Middleware Type Calls `next()` on success or responds with 401 ### Requires `req.user` and `req.proxy` from `authenticate()`. ```