npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@jaaahn/hyper-id-client

v1.0.0-beta.17

Published

For internal use only.

Downloads

12

Readme

HyperID Client Library

This library is for internal use only.

Client

Initialize Auth instance

// auth.js

import { clientInstance } from "@jaaahn/hyper-id-client";

// Create new auth instance
let auth = new clientInstance({
    apiURL: "https://localhost:8080",
    webURL: "https://localhost:3000",
    publicKey: "your_app_public_key",
    includeTokenIn: ["list_of_baseURLs_to_your_first_party_server"],
});

// Add axios interceptors to inject access token in requests (if using axios)
import axios from "axios";
auth.addAxiosInterceptors(axios);

// Mount library on Vue
import router from "./router.js";
auth.installVue(router);

// Catch user updates
let removeUserListener = auth.addEventListener("userChanged", (user) => {
    console.log("user changed", user);

    // DEPRECATION NOTICE: This object includes an `app_data` key. Please use the readAppData() function as the userChanged event won't fire if appData is changed
});

// Catch auth status updates
let removeStatusListener = auth.addEventListener("statusChanged", (status) => {
    console.log("status changed", status);

    // Status syntax
    // {
    //     systemStatus: String; // "initializing" or "loggedOut" or "loggedIn"
    // }
});

let removeRefreshStartedListener = auth.addEventListener("refreshStarted", () => {
    console.log("refresh of token has been triggered");
});

let removeTokenChangedListener = auth.addEventListener("tokenChanged", (token) => {
    console.log("token set", token),

    // NOTE: Use with caution! Nobody should ever get their hands on this token!
})

// Start HyperID
auth.startInitialization();

// Make the instance available to the rest of your application
export default auth;

// Code to remove listeners, if no longer they're needed
/* removeUserListener();
removeStatusListener(); */

Working with Apollo Client

// apollo.js

import { ApolloClient, InMemoryCache, HttpLink } from "@apollo/client/core";
import auth from "./auth.js";

// Create a custom http link
export const apolloHttpLink = new HttpLink({
    uri: "https://localhost:8085/graphql",
});

// HyperID will create a custom ApolloLink and append the provided HttpLink to it
// Will return a link chain of both the HttpLink and HyperID's link
const link = auth.addApolloInterceptors(apolloHttpLink);

// Create ApolloClient
export default new ApolloClient({
    cache: new InMemoryCache(),
    link: link, // With out custom Link chain
});

Open login page

auth.authenticate();

Optional: Provide a route that is opened after login:

auth.authenticate("/my_profile");

Open HyperID account settings page

auth.openAccountSettings();

Logout

await auth.logout();

Refresh token if required

Only use this function if building your own request interceptor or token management system. For usage with axios, socket.io and apollo client, we recommend using the provided request interceptors that handle refreshing the token for you.

await auth.startInitialization();

Get token expiration date

let exp = auth.getTokenExpirationDate();

Get token

let token = auth.getToken();
// USE WITH CAUTION! Tokens should never be exposed or made known to anybody!

Get refresh token

let token = auth.getRefreshToken();
// USE WITH CAUTION! Tokens should never be exposed or made known to anybody!

Get user info (also triggers userChanged event)

await auth.getUser();

DEPRECATION NOTICE: This object includes an app_data key. Please use the readAppData() function as the userChanged event won't fire if appData is changed

Read user's AppData

await auth.readAppData();

Write user's AppData

await auth.writeAppData(data);

The data object should be a dictionary containing key-value pairs.
Only strings can be stored as values. Any non-ASCII characters are automatically removed from keys.
If a key is set to null, it will be deleted from the DB. If an existing key is not mentioned, it won't be touched.
Example:

{
    hello: "world",
    foo: 2, // Will be transformed to string
    bar: true, // Will be transformed to string
    test: null, // Will delete the key `test` from the DB
}

Warning: This does NOT perform escaping so make shure to have a XSS preventioning system implemented if storing user generated content

Server

Initialization

// auth.js

import { serverInstance } from "@jaaahn/hyper-id-client";

// Create new auth server instance
let auth = new serverInstance({
    apiURL: "https://localhost:8080",
    privateKey: "your_app_private_key",
});

export default auth;

Express verify session middleware

// Add the middleware to your routes
// It is important that you call the `auth.express.verifySession` function!

// A valid session is required
app.get("/myRoute", auth.express.verifySession(), (request, response) => {
    let { user, appdata } = request.hyperid;
});

// A valid session is NOT required; the user info will still be available if a user is logged in
app.get("/myRoute", auth.express.verifySession(false), (request, response) => {
    let { user, appdata } = request.hyperid;
});

Apollo verify session (using express server as a base)

Validating a session

// index.js

app.use(
    "/graphql",
    expressMiddleware(server, {
        context: async ({ req, res }) => {
            /**
             * Function parses request, validates a present session and returns the user and appdata
             * Will return { user: null, appdata: null } if a user is not logged in
             */
            let { user, appdata } = await auth.apollo.validateSession(req);

            return { user, appdata, req, res };
        },
    })
);

Enforcing a session

// resolvers.js

Query: {
    async posts(_, args, contextValue) {
        let user = contextValue.user;
        let appdata = contextValue.appdata;

        /**
         * Will throw a GraphQLError if no user is logged in
         */
        auth.apollo.enforceSession(contextValue);

        // Any code to resolve the "posts" query
    },
},

Read user's AppData

await auth.readAppData(user_id);

Write user's AppData

await auth.writeAppData(user_id, data);

The data object should be a dictionary containing key-value pairs.
Only strings can be stored as values. Any non-ASCII characters are automatically removed from keys.
If a key is set to null, it will be deleted from the DB. If an existing key is not mentioned, it won't be touched.
Example:

{
    hello: "world",
    foo: 2, // Will be transformed to string
    bar: true, // Will be transformed to string
    test: null, // Will delete the key `test` from the DB
}

Warning: This does NOT perform escaping so make shure to have a XSS preventioning system implemented if storing user generated content

Get info about app

await auth.getAppInfo();

Get a list of all users

await auth.getAllUsers();

Get one user

await auth.getOneUser(search);

Search by user_id or by email.

Known issues

"ReferenceError: Cannot access uninitialized variable" in a Vue client with Vue Router

If this error message pops up on your client, try importing your auth instance at the top of main.js (at least before importing your router).
You may use this line: import auth from "./auth.js"