@opikey/sdk 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 OPIKey
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,17 @@
1
- # Temporary Holding Version
1
+ # @opikey/sdk
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
+ No runtime dependencies or telemetry. Node 18+, Bun, Deno and edge fetch runtimes.
4
+
5
+ ```ts
6
+ import { Opi, OpiApprovalRequiredError } from '@opikey/sdk';
7
+ const opi = new Opi(); // OPIKEY environment variable; never print it
8
+ const response = await opi.fetch('openai', '/v1/models');
9
+ const names = await opi.loadSecrets({ only: ['OPENAI_API_KEY'] }); // no overrides
10
+ const metadata = await opi.listSecrets();
11
+ ```
12
+
13
+ In non-Node runtimes provide `{ key, baseUrl }` and a `target` object to `loadSecrets`. Variable names must be valid environment identifiers. Names such as `openai` are not automatically mapped to `OPENAI_API_KEY`: name the vault entry as the variable your app expects.
14
+
15
+ Catch `OpiApprovalRequiredError`, wait with `opi.waitForApproval(error.approvalId, { timeoutMs: 120000 })`, then retry the identical request with the `x-opi-approval` header. Other errors extend `OpiError` with a safe `code` and HTTP `status`. Never log native fetch errors, request/response bodies, or credentials. Base URLs require HTTPS, except `http://localhost` for development.
16
+
17
+ Publish only through the pinned GitHub OIDC workflow; no npm token belongs in this repository.
@@ -0,0 +1,53 @@
1
+ export type SecretMetadata = {
2
+ id: string;
3
+ name: string;
4
+ service: string;
5
+ description: string | null;
6
+ environment: string;
7
+ expired: boolean;
8
+ gateway_ready: boolean;
9
+ };
10
+ export declare class OpiError extends Error {
11
+ readonly code: string;
12
+ readonly status: number;
13
+ constructor(code: string, status: number, message?: string);
14
+ }
15
+ export declare class OpiAuthError extends OpiError {
16
+ }
17
+ export declare class OpiForbiddenError extends OpiError {
18
+ }
19
+ export declare class OpiRateLimitError extends OpiError {
20
+ }
21
+ export declare class OpiEncryptionUnavailableError extends OpiError {
22
+ }
23
+ export declare class OpiApprovalRequiredError extends OpiError {
24
+ readonly approvalId: string;
25
+ constructor(code: string, status: number, approvalId: string);
26
+ }
27
+ export declare class OpiTimeoutError extends OpiError {
28
+ }
29
+ export declare function secureBaseUrl(value: string): string;
30
+ export declare function checkResponse(response: Response): Promise<Response>;
31
+ export declare class Opi {
32
+ #private;
33
+ readonly baseUrl: string;
34
+ constructor(options?: {
35
+ key?: string;
36
+ baseUrl?: string;
37
+ });
38
+ toString(): string;
39
+ toJSON(): {
40
+ baseUrl: string;
41
+ key: string;
42
+ };
43
+ fetch(secret: string, path: string, init?: RequestInit): Promise<Response>;
44
+ listSecrets(): Promise<SecretMetadata[]>;
45
+ loadSecrets(options?: {
46
+ target?: Record<string, string | undefined>;
47
+ override?: boolean;
48
+ only?: string[];
49
+ }): Promise<string[]>;
50
+ waitForApproval(id: string, options: {
51
+ timeoutMs: number;
52
+ }): Promise<string>;
53
+ }
package/dist/index.js ADDED
@@ -0,0 +1,77 @@
1
+ export class OpiError extends Error {
2
+ code;
3
+ status;
4
+ constructor(code, status, message = 'OPI request failed.') {
5
+ super(message);
6
+ this.code = code;
7
+ this.status = status;
8
+ this.name = new.target.name;
9
+ }
10
+ }
11
+ export class OpiAuthError extends OpiError {
12
+ }
13
+ export class OpiForbiddenError extends OpiError {
14
+ }
15
+ export class OpiRateLimitError extends OpiError {
16
+ }
17
+ export class OpiEncryptionUnavailableError extends OpiError {
18
+ }
19
+ export class OpiApprovalRequiredError extends OpiError {
20
+ approvalId;
21
+ constructor(code, status, approvalId) {
22
+ super(code, status, 'Owner approval is required.');
23
+ this.approvalId = approvalId;
24
+ }
25
+ }
26
+ export class OpiTimeoutError extends OpiError {
27
+ }
28
+ const env = () => globalThis.process?.env;
29
+ export function secureBaseUrl(value) { const url = new URL(value); if (url.username || url.password || url.search || url.hash || url.pathname !== '/' || !(url.protocol === 'https:' || (url.protocol === 'http:' && url.hostname === 'localhost')))
30
+ throw new OpiError('invalid_base_url', 0, 'Use HTTPS, or http://localhost for development.'); return url.origin; }
31
+ const safeMessages = { invalid_key: 'OPI Key is invalid or revoked.', missing_key: 'An OPI Key is required.', forbidden: 'Access denied.', mode_disabled: 'This connection mode is disabled.', encryption_unavailable: 'Encryption is temporarily unavailable.', external_cost_unavailable: 'A verified price rule is required for this capped call.' };
32
+ export async function checkResponse(response) {
33
+ if (response.ok)
34
+ return response;
35
+ let data;
36
+ try {
37
+ data = await response.clone().json();
38
+ }
39
+ catch { /* Do not echo arbitrary response content. */ }
40
+ const error = data && typeof data === 'object' && 'error' in data && data.error && typeof data.error === 'object' ? data.error : null;
41
+ const code = error && 'code' in error && typeof error.code === 'string' ? error.code : 'request_failed';
42
+ if (code === 'approval_required') {
43
+ const id = error && 'approval_id' in error && typeof error.approval_id === 'string' ? error.approval_id : '';
44
+ throw new OpiApprovalRequiredError(code, response.status, id);
45
+ }
46
+ const Klass = code === 'encryption_unavailable' ? OpiEncryptionUnavailableError : response.status === 401 ? OpiAuthError : response.status === 429 ? OpiRateLimitError : response.status === 403 ? OpiForbiddenError : OpiError;
47
+ throw new Klass(code, response.status, safeMessages[code] ?? 'OPI request failed.');
48
+ }
49
+ export class Opi {
50
+ #key;
51
+ baseUrl;
52
+ constructor(options = {}) { this.#key = options.key ?? env()?.['OPIKEY'] ?? ''; if (!this.#key)
53
+ throw new OpiAuthError('missing_key', 401, 'An OPI Key is required.'); this.baseUrl = secureBaseUrl(options.baseUrl ?? 'https://opikey.ai'); }
54
+ toString() { return 'Opi { key: [hidden] }'; }
55
+ toJSON() { return { baseUrl: this.baseUrl, key: '[hidden]' }; }
56
+ [Symbol.for('nodejs.util.inspect.custom')]() { return this.toString(); }
57
+ async #request(path, init = {}) { const headers = new Headers(init.headers); headers.set('authorization', `Bearer ${this.#key}`); return checkResponse(await globalThis.fetch(this.baseUrl + path, { ...init, headers, redirect: 'manual' })); }
58
+ fetch(secret, path, init = {}) { if (!/^[A-Za-z0-9_.-]{1,64}$/.test(secret) || !path.startsWith('/') || path.startsWith('//'))
59
+ throw new OpiError('invalid_secret', 0, 'Provide a secret name and an absolute API path.'); return this.#request('/api/public/gateway/' + encodeURIComponent(secret) + path, init); }
60
+ async listSecrets() { const response = await this.#request('/api/public/secrets'); return (await response.json()).secrets; }
61
+ async loadSecrets(options = {}) { const target = options.target ?? env(); if (!target)
62
+ throw new OpiError('target_required', 0, 'Provide a target object in this runtime.'); const response = await this.#request('/api/public/secrets-fetch'); const payload = await response.json(); const loaded = []; for (const [name, value] of Object.entries(payload.secrets)) {
63
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name) || ['__proto__', 'prototype', 'constructor'].includes(name) || typeof value !== 'string' || (options.only && !options.only.includes(name)) || (!options.override && Object.hasOwn(target, name)))
64
+ continue;
65
+ target[name] = value;
66
+ loaded.push(name);
67
+ } return loaded; }
68
+ async waitForApproval(id, options) { if (!/^[a-f0-9-]{36}$/i.test(id))
69
+ throw new OpiError('invalid_approval', 0, 'Invalid approval identifier.'); const deadline = Date.now() + options.timeoutMs; while (Date.now() < deadline) {
70
+ const remaining = deadline - Date.now();
71
+ const response = await this.#request('/api/public/approvals/' + encodeURIComponent(id), { signal: AbortSignal.timeout(Math.max(1, remaining)) });
72
+ const result = await response.json();
73
+ if (result.status !== 'pending')
74
+ return result.status;
75
+ await new Promise(r => setTimeout(r, Math.min(1000, Math.max(1, deadline - Date.now()))));
76
+ } throw new OpiTimeoutError('approval_timeout', 0, 'Approval wait timed out.'); }
77
+ }
package/package.json CHANGED
@@ -1,6 +1,49 @@
1
1
  {
2
2
  "name": "@opikey/sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "OPIKey SDK: call any API through your OPI Key, or load your secrets at startup.",
5
+ "keywords": [
6
+ "opikey",
7
+ "api-keys",
8
+ "secrets",
9
+ "ai-agents",
10
+ "gateway"
11
+ ],
12
+ "license": "MIT",
13
+ "homepage": "https://opikey.ai/docs",
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "git+https://github.com/jiayi-app/opikey-js.git",
17
+ "directory": "packages/sdk"
18
+ },
19
+ "bugs": {
20
+ "url": "https://github.com/jiayi-app/opikey-js/issues"
21
+ },
22
+ "type": "module",
23
+ "exports": {
24
+ ".": {
25
+ "types": "./dist/index.d.ts",
26
+ "import": "./dist/index.js"
27
+ }
28
+ },
29
+ "types": "./dist/index.d.ts",
30
+ "files": [
31
+ "dist",
32
+ "README.md",
33
+ "LICENSE"
34
+ ],
35
+ "engines": {
36
+ "node": ">=18"
37
+ },
38
+ "scripts": {
39
+ "build": "tsc -p tsconfig.json",
40
+ "test": "vitest run --config vitest.config.ts"
41
+ },
42
+ "devDependencies": {
43
+ "typescript": "^5.8.3",
44
+ "vitest": "^4.1.10"
45
+ },
46
+ "publishConfig": {
47
+ "access": "public"
48
+ }
49
+ }