Skip to content
extension-core-infrastructure logo

Core Infrastructure

extension-core-infrastructure

Core infrastructure providing backend connection configuration, storage client, and React app entry point.

caffeinelabs/skills24.2Kinstalls2stars

SKILL.md

Full skill instructions

Core Infrastructure

Core infrastructure extension for Caffeine AI.

Overview

This component provides the foundational infrastructure for all projects: backend connection configuration, Internet Identity authentication hooks, and actor management utilities.

Requirements

"@caffeineai/​core-infrastructure": "^1.4.0"
"@caffeineai/​object-storage": "^1.1.0"
"@icp-sdk/​auth": "^7.1.0"
"@icp-sdk/​core": "^5.3.0"

@caffeineai/​object-storage is a peer dependency of core-infrastructure. Every project must install it as a direct npm dependency (the build template includes both packages).

Integration

Core infrastructure is automatically included in every project. No manual integration steps are required.

Frontend

The core-infrastructure frontend package (@caffeineai/​core-infrastructure) is automatically included in every project.

App Entry Point

Wrap the app with InternetIdentityProvider and QueryClientProvider:

import { InternetIdentityProvider } from "@caffeineai/​core-infrastructure";
import { QueryClient, QueryClientProvider } from "@tanstack/​react-query";
import ReactDOM from "react-dom/​client";
import App from "./​App";

const queryClient = new QueryClient();

ReactDOM.createRoot(document.getElementById("root")!).render(
  <QueryClientProvider client={queryClient}>
    <InternetIdentityProvider>
      <App />
    </​InternetIdentityProvider>
  </​QueryClientProvider>,
);

useInternetIdentity() — Authentication Hook

Provides identity state, login, and logout for Internet Identity.

Return Values

FieldTypeDescription
identityIdentity | undefinedThe user's identity (available after login or session restore)
login(options?: LoginOptions) => voidOpens the II popup. Fire-and-forget — do not await. See Sign-in variants.
clear() => voidLogs out and clears stored identity. Fire-and-forget.
isAuthenticatedbooleantrue when user has a valid identity. Use this for UI gating.
isInitializingbooleantrue while AuthClient is loading from IndexedDB
isLoggingInbooleantrue while the II popup is open
isLoginSuccessbooleantrue only after interactive login (NOT after page reload restore)
isLoginErrorbooleantrue if login or initialization failed
loginErrorError | undefinedThe error object when isLoginError is true

Auth State Lifecycle

ScenariologinStatusisAuthenticated
Page load, no stored session"idle"false
Restoring stored session"initializing"false → true
Stored session restored after reload"idle"true
Interactive login in progress"logging-in"false
Interactive login just completed"success"true
Login popup failed / cancelled"loginError"false

IMPORTANT: isLoginSuccess is only true after an interactive login via the popup — NOT when a stored identity is restored on page reload. Always use isAuthenticated for conditional rendering.

Usage

Gate authenticated UI on isAuthenticated:

const { isAuthenticated } = useInternetIdentity();

{isAuthenticated ? <AuthenticatedApp /> : <LoginScreen />}

Disable the login button while initializing or logging in:

const { login, isInitializing, isLoggingIn } = useInternetIdentity();

<button onClick={() => login()} disabled={isInitializing || isLoggingIn}>
  Sign in
</​button>

login() and clear() are fire-and-forget — the hook's state fields (isLoggingIn, isInitializing) track the async lifecycle. Do not wrap them in local useState / isPending logic.

Sign-in variants: plain II, Google, Microsoft, workspace SSO

login() accepts an optional LoginOptions object selecting how the user signs in. All variants go through Internet Identity and produce the same identity, session behavior, and logout — they only change which screen the user sees first:

login();                            // Plain Internet Identity sign-in
login({ provider: "google" });      // One-click Google sign-in (II opens Google OAuth directly)
login({ provider: "microsoft" });   // One-click Microsoft sign-in (II opens Microsoft OAuth directly)
login({ ssoDomain: "acme.com" });   // Company/​workspace SSO via the domain's identity provider
  • Google: no Google API keys or OAuth client setup is needed — Internet Identity handles the OAuth flow.
  • Microsoft: no Azure/​Entra app registration is needed — Internet Identity owns the OAuth client. Accepts both personal Microsoft accounts and work/​school accounts.
  • Workspace SSO: the user enters their company domain (e.g. acme.com); Internet Identity discovers the company's OpenID Connect provider from https://<domain>/​.well-known/​ii-openid-configuration and signs in against it (works with Okta, Entra ID, and other OIDC providers the company has configured). Use this when the app needs a specific company's own tenant; use provider: "microsoft" for a one-click Microsoft button that needs no per-company setup.
  • Apple sign-in is not offered: Internet Identity returns no email or name claims for Apple, so the attribute callback would be empty.
  • Sessions from all variants are stored the same way: isAuthenticated, session restore on reload, and clear() behave identically regardless of the variant used.
  • When the backend uses caffeineai-authorization, Google, Microsoft, and SSO sign-ins carry verified name/​email attributes (and the SSO domain) to the attribute callback automatically — see the extension-authorization skill.

Call login() only from a button's onClick handler. The Internet Identity popup can only be opened while a real click event is dispatching; anything else fails with Signer window should not be opened outside of click handler. In particular:

  • Never call login() from a form's onSubmit — the submit event fires after the click event has finished, so the check fails. For the SSO domain field, use a plain <div> (not a <form>) and a type="button" submit button whose onClick validates the domain and calls login({ ssoDomain }) directly.
  • Never call login() from keyboard handlers (e.g. Enter in the domain input) or after an await — both run outside the click dispatch.

If the app validates the SSO domain before calling login, mirror Internet Identity's own rules: accept a normal DNS name with at least two labels (e.g. acme.com) or a loopback host — localhost or 127.0.0.1, with an optional :port (e.g. localhost:3000). II accepts loopback domains for local testing, so the input must not reject them.

Standard sign-in UI pattern — prominent Google and Microsoft buttons, plain II sign-in, and a "company SSO" option that prompts for a domain:

function SignInOptions() {
  const { login, isInitializing, isLoggingIn } = useInternetIdentity();
  const [ssoDomain, setSsoDomain] = useState("");
  const disabled = isInitializing || isLoggingIn;

  return (
    <div>
      <button onClick={() => login({ provider: "google" })} disabled={disabled}>
        Continue with Google
      </​button>
      <button onClick={() => login({ provider: "microsoft" })} disabled={disabled}>
        Continue with Microsoft
      </​button>
      <button onClick={() => login()} disabled={disabled}>
        Sign in with Internet Identity
      </​button>
      {/​* Company SSO: deliberately not a <form> — login must run inside the
          button's click event, and form onSubmit fires after the click ends */​}
      <input
        value={ssoDomain}
        onChange={(e) => setSsoDomain(e.target.value)}
        placeholder="yourcompany.com"
      />
      <button
        onClick={() => login({ ssoDomain: ssoDomain.trim() })}
        disabled={disabled || !ssoDomain.trim()}
      >
        Sign in with your company
      </​button>
    </​div>
  );
}

Only offer the variants the app actually needs: default to plain login() unless Google, Microsoft, or company SSO sign-in was requested. When one of them is requested, the sign-in page must show the requested direct sign-in option (Google button, Microsoft button, and/​or SSO domain input) and keep a plain "Sign in with Internet Identity" button as a fallback — users without a Google or Microsoft account or a registered company domain must still be able to sign in.

useActor() — Backend Actor Hook

Creates and manages a typed backend actor instance. Automatically re-creates the actor when the user's identity changes (login/​logout).

import { useActor } from "@caffeineai/​core-infrastructure";
import { createActor } from "@/​backend";

function MyComponent() {
  const { actor, isFetching } = useActor(createActor);

  // actor is null while loading, then the typed backend actor
  if (!actor || isFetching) return <Loading />;

  // Call backend methods directly
  const data = await actor.myBackendMethod();
}

Return Values

FieldTypeDescription
actorT | nullThe typed backend actor, or null while loading
isFetchingbooleantrue while the actor is being created

When the identity changes (login, logout, or session restore), the actor is automatically re-created with the new identity and all dependent queries are invalidated and refetched.

Mock backend for visual QA (VITE_USE_MOCK=true)

useActor can serve an app-owned mock instead of connecting to a canister. Put the mock at src/​frontend/​src/​mocks/​backend.ts, exporting mockBackend, and pass the glob from app source:

import { useActor } from "@caffeineai/​core-infrastructure";
import { createActor } from "@/​backend";

const mockModules = import.meta.glob("../​mocks/​backend.{ts,tsx,js,jsx}");

export function useAppActor() {
  return useActor(createActor, { mockModules });
}

The glob has to be written in the app because Vite resolves import.meta.glob relative to the file containing the call; the package cannot see the app's mocks/ directory. Globbing rather than importing keeps the build green when the mock file does not exist. The mock is used only when VITE_USE_MOCK=true; otherwise useActor behaves exactly as before, and the real backend configuration is loaded.

Outside React, createActorWithConfig(createActor, { mockModules }) accepts the same option, and loadMockBackendFromModules(mockModules) resolves the mock on its own.

More skills from caffeinelabs

extension-email-marketing logo
caffeinelabs/skills

extension-email-marketing

Send personalised marketing emails to subscribers with an unsubscribe link.

2 24.3K
View
extension-email-verification logo
caffeinelabs/skills

extension-email-verification

Support for sending an email with a link the recipient can click to prove they own the email address.

2 24.2K
View
extension-object-storage logo
caffeinelabs/skills

extension-object-storage

General file/object storage, such as for images, videos, files, documents and other bulk data. Perfect fit for image galleries, video galleries, and other file or object management. Supports large files beyond IC limit, with browser-cached HTTP URL access.

2 24.2K
View
extension-authorization logo
caffeinelabs/skills

extension-authorization

Authorization system with role-based access control. Must-have for all apps that manage personal or access-restricted data.

2 24.2K
View
extension-email logo
caffeinelabs/skills

extension-email

Support for sending service/transactional emails. Don't use this for sending marketing emails or verification emails.

2 24.2K
View
extension-http-outcalls logo
caffeinelabs/skills

extension-http-outcalls

HTTP outcalls performed by the backend canister (not in the frontend).

2 24.2K
View
extension-invite-links logo
caffeinelabs/skills

extension-invite-links

Requests invite-link / RSVP based access where guests can submit responses without login while admin can view responses with login.

2 24.2K
View
extension-email-raw logo
caffeinelabs/skills

extension-email-raw

Send an email with multiple to, cc and bcc addresses.

2 24.2K
View
extension-openai logo
caffeinelabs/skills

extension-openai

MANDATORY recipe for every Caffeine build that calls OpenAI (ChatGPT, GPT-4o, an LLM, a chatbot, embeddings). The ONLY supported path is the `openai-client` mops package with a canister-side API-key bearer. Hand-rolling `ic.http_request` to `api.openai.com/v1/...` is a FORBIDDEN anti-pattern — it leaks the bearer across replicated outcalls (security + 13× billing impact), bypasses the typed request/response bindings, and forces hand-rolled JSON on a language with poor JSON support. Load this skill whenever the user, spec, or any prior task mentions ChatGPT, GPT (any version), OpenAI, an LLM, a chatbot, or embeddings — and BEFORE writing any code that touches `api.openai.com`.

2 24.2K
View
extension-posting-to-x logo
caffeinelabs/skills

extension-posting-to-x

MANDATORY recipe for every Caffeine build that posts to X (Twitter). The ONLY supported path is the `x-client` mops package with OAuth 2.0 PKCE. Hand-rolling `ic.http_request` or `icBooking.http_request` calls to `api.x.com/2/tweets`, `api.x.com/2/oauth2/token`, or any other X endpoint is a FORBIDDEN anti-pattern — it bypasses bearer auth, replication-cost safeguards, and `x-client`'s null-field handling. Load this skill whenever the user, spec, or any prior task mentions tweeting, live-tweeting, posting-to-X, posting-a-status, sharing-to-Twitter, or any equivalent phrasing — and BEFORE writing any code that touches `api.x.com`.

2 24.2K
View
extension-oql logo
caffeinelabs/skills

extension-oql

Make a canister's data queryable by the Caffeine Data Intelligence agent. Use whenever an app stores structured data (Maps/Lists/arrays of records) that should be answerable in natural language — "top customers", "revenue by region", "active projects". Adds a discoverable `schema()` and a JSON `execute()` query endpoint via the `caffeineai-oql` mops package's `Expose` mixin.

2 23.8K
View

Popular AI tools

Kaiber logo
Video

Kaiber

Generate, edit, and beat-sync AI video with leading models in one workspace.

Paid
View
Vimcal logo
Productivity

Vimcal

The world's fastest calendar for remote work

Free
View

Transform Your Design with AI Designer by ImgCreator.ai

Freemium
View
Akool AI logo
Content & writing

Akool AI

Revolutionizing Video Production with AI-Powered Creativity

Paid
View

Extend an image past the frame and let AI fill the new aspect ratio.

Freemium
View
StarByFace logo
Security

StarByFace

Discover your celebrity doppelgänger with StarByFace!

Free
View
C

ChainClarity explains 700+ crypto whitepapers in plain English, with layered summaries, comparisons, research tools, alerts, and a $4.99 Pro plan.

Freemium
View
Opus Clip logo
Coding & apps

Opus Clip

Opus.ai: Revolutionize Your Web Experience

Free
View