caffeinelabs/skills

extension-core-infrastructure

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

ソースを見る
リポジトリの原文

見出し、例、コード、表、リンク、参照画像を含む原文を表示しています。

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.2.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:

typescript
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
identity`Identity \undefined`The 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
loginError`Error \undefined`The error object when isLoginError is true

Auth State Lifecycle

ScenariologinStatusisAuthenticated
Page load, no stored session"idle"false
Restoring stored session"initializing"falsetrue
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:

typescript
const { isAuthenticated } = useInternetIdentity();

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

Disable the login button while initializing or logging in:

typescript
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:

typescript
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:

typescript
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).

typescript
import { useActor } from "@caffeineai/core-infrastructure";
import { createActor } from "declarations/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
actor`T \null`The 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.

同じリポジトリから

関連する Skills

すべての Skills
caffeinelabs
コミュニティ

connector-googlecalendar

- MANDATORY recipe for every Caffeine build that lists upcoming events or creates events on the user's own Google Calendar. The ONLY supported path is the googlecalendar-client mops package (Calendar REST API v3) combined with the google-oauth mops package (token exchange + refresh + PKCE). Hand-rolling ic.httprequest calls to oauth2.googleapis.com or www.googleapis.com/calendar/v3 is a FORBIDDEN anti-pattern — it bypasses bearer auth, replication-cost safeguards, and the google-oauth library's percent-encoding and JSON parsing. Load this skill whenever the user, spec, or any prior task mentions scheduling, calendar events, appointments, meetings, "add to calendar", or any equivalent phrasing — and BEFORE writing any code that touches a Google endpoint.

導入数
2
GitHub Stars
0
更新日
9月4日
caffeinelabs
コミュニティ

connector-googlemail

- MANDATORY recipe for every Caffeine build that sends email through the user's own Gmail account. The ONLY supported path is the googlemail-client mops package (Gmail REST API) combined with the google-oauth mops package (token exchange + refresh + PKCE). Hand-rolling ic.httprequest calls to oauth2.googleapis.com or gmail.googleapis.com is a FORBIDDEN anti-pattern — it bypasses bearer auth, replication-cost safeguards, and the google-oauth library's percent-encoding and JSON parsing. Load this skill whenever the user, spec, or any prior task mentions sending email, Gmail, "notify via email", "forward results by email", or any equivalent phrasing — and BEFORE writing any code that touches a Google endpoint.

導入数
2
GitHub Stars
0
更新日
9月4日
caffeinelabs
コミュニティ

connector-slack

- EXPERIMENTAL, UNTESTED recipe for posting messages to a Slack workspace from a Caffeine canister via the slack-client mops package (Slack Web API). Use it when the user wants their app to send a message to a Slack channel — "post to Slack", "notify a channel", "send a Slack message", or equivalent. The client is a pre-release 0.1.0 drop (bot xoxb- or user xoxp- token): its request path is verified against the live Slack API (a real message posts), but the success-response decode is not yet runtime-confirmed, so treat it as a starting point and do NOT present Slack as a fully supported platform feature yet. Hand-rolling ic.httprequest calls to slack.com/api is still the wrong move — prefer the generated client so bearer auth, percent-encoding, and JSON parsing come for free.

導入数
2
GitHub Stars
0
更新日
9月4日
caffeinelabs
コミュニティ

connector-twilio

- EXPERIMENTAL, NOT YET VERIFIED AGAINST LIVE TWILIO, and it spends real money — every message is billed, and a US-bound production number additionally needs A2P 10DLC registration (fees, weeks of lead time). Say both things to the user before building. That said, if a Caffeine build does send SMS or MMS, or configures Twilio messaging, from a canister, the twilio-client mops package (Twilio REST API) with a canister-held HTTP Basic credential is the only supported path. Hand-rolling ic.httprequest calls to api.twilio.com or messaging.twilio.com is a FORBIDDEN anti-pattern — it bypasses the typed bindings, the per-operation host routing, the Basic-Auth header construction, and above all the non-replicated outcall default that stops one send from becoming ~13 billed messages. Load this skill whenever the user, spec, or any prior task mentions SMS, MMS, "text message", "send a text", phone numbers, Twilio, a Messaging Service, A2P 10DLC, toll-free verification, short codes, or an alphanumeric sender — and BEFORE writing any code that touches a Twilio endpoint.

導入数
2
GitHub Stars
0
更新日
9月4日