@characterxyz/server 0.0.0-stage → 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 Charky Labs Pvt Ltd
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 CHANGED
@@ -1,3 +1,18 @@
1
- # Temporary Holding Version
1
+ # @characterxyz/server
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Character XYZ on your server. Mint a session for a signed-in visitor with your secret key, and verify
4
+ webhook signatures. Works in Node 18+, Deno, Bun and edge runtimes.
5
+
6
+ ```ts
7
+ import { createSession, verifyWebhook } from '@characterxyz/server';
8
+
9
+ const session = await createSession({
10
+ secretKey: process.env.CHARACTERXYZ_SECRET_KEY!,
11
+ visitor: { id: user.id },
12
+ origin: 'https://www.example.com',
13
+ });
14
+ ```
15
+
16
+ A secret key never belongs in a browser: `createSession` refuses to run in one.
17
+
18
+ See the [repository README](https://github.com/characterxyz/characterxyz-sdk#readme) for usage, security and customising.
@@ -0,0 +1,54 @@
1
+ import { SessionInfo } from '@characterxyz/web';
2
+ export { SessionInfo } from '@characterxyz/web';
3
+
4
+ /**
5
+ * `@characterxyz/server` — mint a session for a SIGNED-IN visitor, on
6
+ * your server, with your secret key; verify webhooks. Node 18+, Deno, Bun,
7
+ * edge runtimes. Zero dependencies at runtime.
8
+ *
9
+ * ```ts
10
+ * // e.g. a Next.js route handler: GET /api/characterxyz/session
11
+ * import { createSession } from '@characterxyz/server';
12
+ *
13
+ * export async function GET() {
14
+ * const user = await currentUser();
15
+ * const session = await createSession({
16
+ * secretKey: process.env.CHARACTERXYZ_SECRET_KEY!,
17
+ * visitor: { id: user.id },
18
+ * origin: 'https://www.example.com',
19
+ * });
20
+ * return Response.json(session);
21
+ * }
22
+ * ```
23
+ *
24
+ * Then in the page: `CharacterXYZ.init({ getSessionToken: () => fetch('/api/characterxyz/session').then(r => r.json()) })`.
25
+ * The visitor's chat history then follows them across devices, and webhooks
26
+ * carry your id for them as `externalId`.
27
+ */
28
+
29
+ interface CreateSessionOptions {
30
+ /** `cxyz_sk_…` — from your server's environment, never from code. */
31
+ secretKey: string;
32
+ /** Your id for this person (≤ 128 characters). Omit for an anonymous visitor. */
33
+ visitor?: {
34
+ id: string;
35
+ };
36
+ agentId?: string;
37
+ /** The site the session will be used from; binds it there. Must be on the key. */
38
+ origin?: string;
39
+ apiUrl?: string;
40
+ }
41
+ declare function createSession(opts: CreateSessionOptions): Promise<SessionInfo>;
42
+ /**
43
+ * Check a webhook's `Cxyz-Signature` header. Pass the RAW body string, exactly
44
+ * as received. Rejects anything older than `toleranceSeconds` (default 300).
45
+ */
46
+ declare function verifyWebhook(opts: {
47
+ secret: string;
48
+ body: string;
49
+ signature: string | null;
50
+ toleranceSeconds?: number;
51
+ now?: number;
52
+ }): Promise<boolean>;
53
+
54
+ export { type CreateSessionOptions, createSession, verifyWebhook };
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ async function g(e){if(typeof window<"u"&&typeof document<"u")throw new Error("createSession runs on your server. A secret key must never reach a browser.");let s=(e.apiUrl??"https://api.character.xyz").replace(/\/+$/,""),r=await fetch(`${s}/sdk/v1/sessions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e.secretKey}`},body:JSON.stringify({agentId:e.agentId,visitor:e.visitor,origin:e.origin})}),n=await r.json().catch(()=>({}));if(!r.ok||!n.data)throw new Error(`Character XYZ session failed (${r.status}): ${n.message??"unknown error"}`);return n.data}async function l(e){let s=e.signature??"",r=Object.fromEntries(s.split(",").map(t=>t.split("=",2))),n=Number(r.t),o=r.v1;if(!n||!o)return false;let c=e.now??Math.floor(Date.now()/1e3);if(Math.abs(c-n)>(e.toleranceSeconds??300))return false;let d=await crypto.subtle.importKey("raw",new TextEncoder().encode(e.secret),{name:"HMAC",hash:"SHA-256"},false,["sign"]),f=new Uint8Array(await crypto.subtle.sign("HMAC",d,new TextEncoder().encode(`${n}.${e.body}`))),i=Array.from(f,t=>t.toString(16).padStart(2,"0")).join("");if(i.length!==o.length)return false;let a=0;for(let t=0;t<i.length;t++)a|=i.charCodeAt(t)^o.charCodeAt(t);return a===0}
2
+ export{g as createSession,l as verifyWebhook};//# sourceMappingURL=index.js.map
3
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts"],"names":["createSession","opts","apiUrl","res","body","verifyWebhook","sig","parts","p","t","v1","now","key","mac","expected","b","diff","i"],"mappings":"AAqCA,eAAsBA,CAAAA,CAAcC,CAAAA,CAAkD,CACpF,GAAI,OAAO,MAAA,CAAW,GAAA,EAAe,OAAO,QAAA,CAAa,GAAA,CACvD,MAAM,IAAI,KAAA,CAAM,6EAA6E,CAAA,CAE/F,IAAMC,CAAAA,CAAAA,CAAUD,CAAAA,CAA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OD,CAAAA,GAAS,CAClB","file":"index.js","sourcesContent":["/**\n * `@characterxyz/server` — mint a session for a SIGNED-IN visitor, on\n * your server, with your secret key; verify webhooks. Node 18+, Deno, Bun,\n * edge runtimes. Zero dependencies at runtime.\n *\n * ```ts\n * // e.g. a Next.js route handler: GET /api/characterxyz/session\n * import { createSession } from '@characterxyz/server';\n *\n * export async function GET() {\n * const user = await currentUser();\n * const session = await createSession({\n * secretKey: process.env.CHARACTERXYZ_SECRET_KEY!,\n * visitor: { id: user.id },\n * origin: 'https://www.example.com',\n * });\n * return Response.json(session);\n * }\n * ```\n *\n * Then in the page: `CharacterXYZ.init({ getSessionToken: () => fetch('/api/characterxyz/session').then(r => r.json()) })`.\n * The visitor's chat history then follows them across devices, and webhooks\n * carry your id for them as `externalId`.\n */\nimport type { SessionInfo } from '@characterxyz/web';\n\nexport interface CreateSessionOptions {\n /** `cxyz_sk_…` — from your server's environment, never from code. */\n secretKey: string;\n /** Your id for this person (≤ 128 characters). Omit for an anonymous visitor. */\n visitor?: { id: string };\n agentId?: string;\n /** The site the session will be used from; binds it there. Must be on the key. */\n origin?: string;\n apiUrl?: string;\n}\n\nexport async function createSession(opts: CreateSessionOptions): Promise<SessionInfo> {\n if (typeof window !== 'undefined' && typeof document !== 'undefined') {\n throw new Error('createSession runs on your server. A secret key must never reach a browser.');\n }\n const apiUrl = (opts.apiUrl ?? 'https://api.character.xyz').replace(/\\/+$/, '');\n const res = await fetch(`${apiUrl}/sdk/v1/sessions`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${opts.secretKey}` },\n body: JSON.stringify({ agentId: opts.agentId, visitor: opts.visitor, origin: opts.origin }),\n });\n const body = (await res.json().catch(() => ({}))) as { data?: SessionInfo; message?: string };\n if (!res.ok || !body.data) throw new Error(`Character XYZ session failed (${res.status}): ${body.message ?? 'unknown error'}`);\n return body.data;\n}\n\n/**\n * Check a webhook's `Cxyz-Signature` header. Pass the RAW body string, exactly\n * as received. Rejects anything older than `toleranceSeconds` (default 300).\n */\nexport async function verifyWebhook(opts: { secret: string; body: string; signature: string | null; toleranceSeconds?: number; now?: number }): Promise<boolean> {\n const sig = opts.signature ?? '';\n const parts = Object.fromEntries(sig.split(',').map((p) => p.split('=', 2) as [string, string]));\n const t = Number(parts.t);\n const v1 = parts.v1;\n if (!t || !v1) return false;\n const now = opts.now ?? Math.floor(Date.now() / 1000);\n if (Math.abs(now - t) > (opts.toleranceSeconds ?? 300)) return false;\n const key = await crypto.subtle.importKey('raw', new TextEncoder().encode(opts.secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);\n const mac = new Uint8Array(await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(`${t}.${opts.body}`)));\n const expected = Array.from(mac, (b) => b.toString(16).padStart(2, '0')).join('');\n if (expected.length !== v1.length) return false;\n let diff = 0;\n for (let i = 0; i < expected.length; i++) diff |= expected.charCodeAt(i) ^ v1.charCodeAt(i);\n return diff === 0;\n}\n\nexport type { SessionInfo };\n"]}
package/package.json CHANGED
@@ -1,6 +1,41 @@
1
1
  {
2
2
  "name": "@characterxyz/server",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "Character XYZ on your server: mint a session for a signed-in visitor with your secret key, and verify webhook signatures. Node, Deno, Bun and edge runtimes.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "sideEffects": false,
8
+ "main": "./dist/index.js",
9
+ "module": "./dist/index.js",
10
+ "types": "./dist/index.d.ts",
11
+ "exports": {
12
+ ".": {
13
+ "types": "./dist/index.d.ts",
14
+ "import": "./dist/index.js"
15
+ },
16
+ "./package.json": "./package.json"
17
+ },
18
+ "files": [
19
+ "dist",
20
+ "README.md",
21
+ "LICENSE"
22
+ ],
23
+ "dependencies": {
24
+ "@characterxyz/web": "^0.1.0"
25
+ },
26
+ "publishConfig": {
27
+ "access": "public",
28
+ "registry": "https://registry.npmjs.org/"
29
+ },
30
+ "repository": {
31
+ "type": "git",
32
+ "url": "https://github.com/characterxyz/characterxyz-sdk.git",
33
+ "directory": "packages/server"
34
+ },
35
+ "homepage": "https://character.xyz",
36
+ "scripts": {
37
+ "build": "tsup",
38
+ "typecheck": "tsc -p tsconfig.json --noEmit",
39
+ "test": "vitest run"
40
+ }
6
41
  }