@gemina/elements 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Gemina
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,256 @@
1
+ # @gemina/elements
2
+
3
+ Embeddable browser UI for [Gemina](https://gemina.co) Document Intelligence:
4
+ a drop-in React chat component (`<GeminaChat>`) plus a security-hardened
5
+ session-token manager (`GeminaTokenManager`). Ask natural-language questions
6
+ about the invoices and financial documents you've processed with Gemina and
7
+ get grounded answers with document citations — without ever exposing your
8
+ Gemina API key to the browser.
9
+
10
+ ## Install
11
+
12
+ ```bash
13
+ npm i @gemina/elements @gemina/sdk react
14
+ ```
15
+
16
+ - `react >= 18` is a peer dependency.
17
+ - `react-dom` is only needed by *your* app to render (and by the bundled
18
+ demo) — the library itself never imports it.
19
+ - `GeminaTokenManager` has zero dependencies and no React requirement:
20
+ import it alone via `@gemina/elements/token-manager`.
21
+
22
+ Subpath exports:
23
+
24
+ | Import | Contents | Needs React? |
25
+ |---|---|---|
26
+ | `@gemina/elements` | Everything | For `GeminaChat` only |
27
+ | `@gemina/elements/token-manager` | `GeminaTokenManager` | No |
28
+ | `@gemina/elements/chat` | `<GeminaChat>` | Yes |
29
+
30
+ ## The security model (read this first)
31
+
32
+ Your Gemina **API key is a master key** — it can upload, read everything,
33
+ delete, and purge. It must live only on your server. The browser gets a
34
+ **short-lived (≤ 15 min), signed, query-only session token** instead:
35
+
36
+ ```
37
+ ┌─────────────────┐ 1. POST /api/gemina-session ┌──────────────────┐
38
+ │ Browser │ ───(your own auth: cookie/JWT)────► │ YOUR backend │
39
+ │ │ │ (holds the │
40
+ │ GeminaTokenMgr │ │ API key) │
41
+ │ + GeminaChat │ ◄──{ token, expiresIn }─────────────│ │
42
+ └───────┬─────────┘ 4. └───────┬──────────┘
43
+ │ │ 2. POST /v1/sessions/token
44
+ │ 5. POST /v1/chat/query │ X-API-Key: <API key>
45
+ │ Authorization: Bearer <session token> ▼
46
+ │ ┌──────────────────┐
47
+ └─────────────────────────────────────────────► │ Gemina API │
48
+ │ 3. mints signed, │
49
+ │ scoped token │
50
+ └──────────────────┘
51
+ ```
52
+
53
+ 1. The browser asks **your backend** for a session token, authenticated by
54
+ your existing user session.
55
+ 2. Your backend calls Gemina's mint endpoint
56
+ (`POST /api/v1/sessions/token`, `sessions.mintRetrievalToken` in
57
+ `@gemina/sdk`) with your **API key — server-side only**.
58
+ 3. Gemina returns a signed, query-only token pinned to your account
59
+ (optionally narrowed to one `endUserId`). Scope is **signed into the
60
+ token**; the browser cannot widen it.
61
+ 4. Your backend hands the token (never the key) to the browser.
62
+ 5. The chat component calls Gemina with the token; Gemina validates
63
+ signature, expiry, and scope on every call.
64
+
65
+ ## `GeminaTokenManager`
66
+
67
+ Holds the session token **in memory only** and keeps it fresh.
68
+
69
+ ```ts
70
+ import { GeminaTokenManager } from "@gemina/elements/token-manager";
71
+
72
+ const tokenManager = new GeminaTokenManager({
73
+ // Points at YOUR backend — see the mint endpoint below.
74
+ fetchToken: async () => {
75
+ const res = await fetch("/api/gemina-session", { method: "POST" });
76
+ if (!res.ok) throw new Error("Failed to mint Gemina session token");
77
+ return res.json(); // { token, expiresIn }
78
+ },
79
+ // Optional: seconds before expiry to refresh (default 60).
80
+ refreshSkewSeconds: 60,
81
+ });
82
+ ```
83
+
84
+ - `getToken(): Promise<string>` — fetches lazily on first use, caches, and
85
+ auto-refreshes once the token is within `refreshSkewSeconds` of expiry.
86
+ Concurrent callers share a single in-flight fetch (no request stampede).
87
+ - `invalidate(): void` — drops the cached token so the next `getToken()`
88
+ re-mints (used internally by `<GeminaChat>` on a 401).
89
+ - No timers run while idle; refresh happens lazily inside `getToken()`, so
90
+ it is SSR-safe and never keeps a Node process alive.
91
+ - The token is stored in module-private state (a `WeakMap` keyed by the
92
+ instance), not as an instance property — it won't show up in
93
+ `JSON.stringify`, spreads, or casual devtools inspection. This is
94
+ hardening against accidental exposure, not encryption.
95
+
96
+ ### The mint endpoint (server-side, yours)
97
+
98
+ Your backend mints tokens with `@gemina/sdk` — **this code must never run
99
+ in a browser**:
100
+
101
+ ```ts
102
+ // Express
103
+ import express from "express";
104
+ import { GeminaClient } from "@gemina/sdk";
105
+
106
+ const gemina = new GeminaClient(process.env.GEMINA_API_KEY!);
107
+ const app = express();
108
+
109
+ app.post("/api/gemina-session", requireYourAppAuth, async (req, res) => {
110
+ const minted = await gemina.sessions.mintRetrievalToken({
111
+ sessionTokenInDTO: {
112
+ // Optional: narrow this session to one of your end-users. The scope
113
+ // is SIGNED into the token — the browser can't change it.
114
+ endUserId: req.user.id,
115
+ ttlSeconds: 900, // clamped server-side to [300, 900]
116
+ },
117
+ });
118
+ res.json({ token: minted.token, expiresIn: minted.expiresIn });
119
+ });
120
+ ```
121
+
122
+ ```ts
123
+ // Next.js (App Router) — app/api/gemina-session/route.ts
124
+ import { NextResponse } from "next/server";
125
+ import { GeminaClient } from "@gemina/sdk";
126
+
127
+ const gemina = new GeminaClient(process.env.GEMINA_API_KEY!);
128
+
129
+ export async function POST(request: Request) {
130
+ const user = await requireYourAppAuth(request); // your session check
131
+ const minted = await gemina.sessions.mintRetrievalToken({
132
+ sessionTokenInDTO: { endUserId: user.id, ttlSeconds: 900 },
133
+ });
134
+ return NextResponse.json({ token: minted.token, expiresIn: minted.expiresIn });
135
+ }
136
+ ```
137
+
138
+ ## `<GeminaChat>`
139
+
140
+ ```tsx
141
+ import { GeminaChat } from "@gemina/elements";
142
+
143
+ <GeminaChat
144
+ tokenManager={tokenManager}
145
+ onCitationClick={(documentId) => openDocumentViewer(documentId)}
146
+ />;
147
+ ```
148
+
149
+ ### Props
150
+
151
+ | Prop | Type | Default | Description |
152
+ |---|---|---|---|
153
+ | `tokenManager` | `GeminaTokenManager` | **required** | Session-token source. |
154
+ | `baseUrl` | `string` | `https://api.gemina.co` | Gemina API base URL. |
155
+ | `endUserId` | `string` | — | Forwarded with each query. On the token path the token's **signed** scope always wins server-side — this is a hint, not a security control. |
156
+ | `theme` | `"light" \| "dark" \| "auto"` | `"auto"` | `"auto"` follows `prefers-color-scheme`. |
157
+ | `dir` | `"ltr" \| "rtl" \| "auto"` | `"auto"` | `"auto"` flips the widget to RTL when the user's latest message contains Hebrew; bubbles also self-resolve via `dir="auto"`. |
158
+ | `placeholder` | `string` | `"Ask about your documents…"` | Input placeholder. |
159
+ | `onCitationClick` | `(documentId: string) => void` | — | Called when a citation chip is clicked. |
160
+ | `className` | `string` | — | Extra class(es) on the root (handy for CSS-variable overrides). |
161
+
162
+ Answers arrive with `documentId` citations rendered as chips; answers the
163
+ backend marks `confident: false` get a visually distinct low-confidence
164
+ treatment. Enter sends, Shift+Enter inserts a newline. The message list is
165
+ a `role="log"` live region with `aria-busy` while a reply is in flight, and
166
+ the input and send button are ARIA-labelled.
167
+
168
+ ### Error behavior
169
+
170
+ | API response | What the widget does |
171
+ |---|---|
172
+ | `401` | `tokenManager.invalidate()` + one automatic retry with a fresh token; if the retry also 401s → "Session expired — please reload the page or sign in again." |
173
+ | `429` | "You're sending messages too quickly — try again shortly." |
174
+ | `402` / `403` | "Document Intelligence isn't enabled on this plan." |
175
+ | anything else | Generic failure with a **Retry** button that resends the last message. |
176
+
177
+ ### Theming
178
+
179
+ Styles are injected once, on mount, into a `<style data-gemina-chat>` tag.
180
+ All class names are scoped under `.gemina-chat`, and every color/shape is a
181
+ CSS custom property you can override from your own stylesheet (or via
182
+ `className`/inline style):
183
+
184
+ ```css
185
+ .my-app .gemina-chat {
186
+ --gemina-chat-accent: #7c3aed;
187
+ --gemina-chat-radius: 4px;
188
+ }
189
+ ```
190
+
191
+ | Variable | Purpose |
192
+ |---|---|
193
+ | `--gemina-chat-bg` / `--gemina-chat-fg` | Widget background / text |
194
+ | `--gemina-chat-border` | Borders (frame, input, chips) |
195
+ | `--gemina-chat-accent` / `--gemina-chat-accent-fg` | User bubble, send button, focus ring, citation chips |
196
+ | `--gemina-chat-assistant-bg` / `--gemina-chat-assistant-fg` | Assistant bubble |
197
+ | `--gemina-chat-muted` | Secondary text ("Thinking…") |
198
+ | `--gemina-chat-error` | Error messages and the retry button |
199
+ | `--gemina-chat-low-confidence` | Low-confidence border/caption |
200
+ | `--gemina-chat-radius` | Corner radius |
201
+ | `--gemina-chat-font` | Font stack |
202
+
203
+ `theme="dark"` (or `"auto"` under a dark `prefers-color-scheme`) swaps the
204
+ variable defaults; explicit overrides via the variables above always win.
205
+
206
+ ### RTL
207
+
208
+ `dir="auto"` (the default) renders LTR until the user writes Hebrew, then
209
+ flips the widget to RTL; individual bubbles resolve their own direction so
210
+ mixed-language conversations stay readable. Pass `dir="rtl"` or
211
+ `dir="ltr"` to pin it.
212
+
213
+ ### SSR
214
+
215
+ Importing either module touches no `window`/`document`, and no timers are
216
+ created at construction — safe for Next.js/Remix server rendering. Style
217
+ injection happens in an effect (mount, client-only). Render `<GeminaChat>`
218
+ normally; it becomes interactive on hydration.
219
+
220
+ ## What this package refuses to do
221
+
222
+ The five footguns from Gemina's token spec, designed out:
223
+
224
+ 1. **Put the API key in the browser.** `GeminaTokenManager` throws at
225
+ construction if handed a raw string, and rejects any API-key-shaped
226
+ (32-alphanumeric) credential coming out of `fetchToken`. Non-JWT tokens
227
+ are rejected too.
228
+ 2. **Persist the token.** No `localStorage`, `sessionStorage`, cookies, or
229
+ IndexedDB anywhere in this package — in-memory only, in module-private
230
+ state. (A test suite enforces this.)
231
+ 3. **Assert its own identity or scope.** Scope lives in the token's signed
232
+ claims; the server derives every data filter from them. `endUserId` on
233
+ the browser path is a hint the server ignores in favor of the signature.
234
+ 4. **Reuse login credentials.** Session tokens come only from
235
+ `POST /v1/sessions/token`; the widget never touches Gemina login JWTs.
236
+ 5. **Mint, hold refresh tokens, or widen TTL/scope.** Renewal always
237
+ round-trips through *your* authenticated backend via `fetchToken`.
238
+
239
+ ## Demo
240
+
241
+ A no-build-system manual demo lives in [`demo/`](./demo). From
242
+ `packages/elements/`:
243
+
244
+ ```bash
245
+ npx esbuild demo/demo.tsx --bundle --outfile=demo/demo.js --jsx=automatic \
246
+ --define:process.env.NODE_ENV='"production"'
247
+ npx serve demo
248
+ ```
249
+
250
+ Mint a session token server-side (see the comment in `demo/index.html`),
251
+ paste it into the page, and mount the chat. The demo never touches an API
252
+ key.
253
+
254
+ ## License
255
+
256
+ MIT