@kmlckj/licos-platform-sdk 0.6.8 → 0.8.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/README.md +100 -47
- package/dist/index.d.ts +180 -0
- package/dist/index.js +1 -1
- package/dist/oauth-runtime.js +1 -0
- package/dist/oauth.js +1 -0
- package/dist/runtime.js +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -17,50 +17,50 @@ is resolved automatically by the runtime:
|
|
|
17
17
|
|
|
18
18
|
## Database
|
|
19
19
|
|
|
20
|
-
Database CRUD helpers call the runtime database data plane only. Tooling helpers
|
|
21
|
-
can fetch platform schema metadata for ORM export. The SDK does not expose
|
|
22
|
-
service deletion APIs.
|
|
23
|
-
|
|
24
|
-
`database.table(name)` is a query builder. Use it for `select` queries only.
|
|
25
|
-
|
|
26
|
-
```js
|
|
27
|
-
import { database } from '@kmlckj/licos-platform-sdk';
|
|
28
|
-
|
|
29
|
-
const rows = await database
|
|
20
|
+
Database CRUD helpers call the runtime database data plane only. Tooling helpers
|
|
21
|
+
can fetch platform schema metadata for ORM export. The SDK does not expose
|
|
22
|
+
service deletion APIs.
|
|
23
|
+
|
|
24
|
+
`database.table(name)` is a query builder. Use it for `select` queries only.
|
|
25
|
+
|
|
26
|
+
```js
|
|
27
|
+
import { database } from '@kmlckj/licos-platform-sdk';
|
|
28
|
+
|
|
29
|
+
const rows = await database
|
|
30
30
|
.table('todos')
|
|
31
31
|
.select('id', 'title')
|
|
32
32
|
.eq('done', false)
|
|
33
33
|
.order('created_at', { desc: true })
|
|
34
|
-
.limit(10)
|
|
35
|
-
.execute();
|
|
36
|
-
```
|
|
37
|
-
|
|
38
|
-
Use top-level helpers for mutations:
|
|
39
|
-
|
|
40
|
-
```js
|
|
41
|
-
import { database } from '@kmlckj/licos-platform-sdk';
|
|
42
|
-
|
|
43
|
-
const inserted = await database.insert('todos', {
|
|
44
|
-
row: { title: 'Call customer', done: false },
|
|
45
|
-
returning: true,
|
|
46
|
-
});
|
|
47
|
-
|
|
48
|
-
await database.updateRows('todos', {
|
|
49
|
-
filters: [{ field: 'id', op: 'eq', value: inserted.data?.[0]?.id }],
|
|
50
|
-
values: { done: true },
|
|
51
|
-
});
|
|
52
|
-
|
|
53
|
-
await database.deleteRows('todos', {
|
|
54
|
-
filters: [{ field: 'done', op: 'eq', value: true }],
|
|
55
|
-
});
|
|
56
|
-
```
|
|
57
|
-
|
|
58
|
-
Do not call `.table('todos').insert(...)`, `.table('todos').updateRows(...)`,
|
|
59
|
-
or `.table('todos').deleteRows(...)`; those methods do not exist on the query
|
|
60
|
-
builder.
|
|
61
|
-
|
|
62
|
-
ORM export is a tooling helper. It fetches platform schema metadata and returns
|
|
63
|
-
source text; it does not use direct database credentials.
|
|
34
|
+
.limit(10)
|
|
35
|
+
.execute();
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
Use top-level helpers for mutations:
|
|
39
|
+
|
|
40
|
+
```js
|
|
41
|
+
import { database } from '@kmlckj/licos-platform-sdk';
|
|
42
|
+
|
|
43
|
+
const inserted = await database.insert('todos', {
|
|
44
|
+
row: { title: 'Call customer', done: false },
|
|
45
|
+
returning: true,
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
await database.updateRows('todos', {
|
|
49
|
+
filters: [{ field: 'id', op: 'eq', value: inserted.data?.[0]?.id }],
|
|
50
|
+
values: { done: true },
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
await database.deleteRows('todos', {
|
|
54
|
+
filters: [{ field: 'done', op: 'eq', value: true }],
|
|
55
|
+
});
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
Do not call `.table('todos').insert(...)`, `.table('todos').updateRows(...)`,
|
|
59
|
+
or `.table('todos').deleteRows(...)`; those methods do not exist on the query
|
|
60
|
+
builder.
|
|
61
|
+
|
|
62
|
+
ORM export is a tooling helper. It fetches platform schema metadata and returns
|
|
63
|
+
source text; it does not use direct database credentials.
|
|
64
64
|
|
|
65
65
|
```js
|
|
66
66
|
import { database } from '@kmlckj/licos-platform-sdk';
|
|
@@ -68,11 +68,11 @@ import { database } from '@kmlckj/licos-platform-sdk';
|
|
|
68
68
|
const source = await database.exportOrm({ language: 'typescript', orm: 'drizzle' });
|
|
69
69
|
```
|
|
70
70
|
|
|
71
|
-
Studio project database management is exposed through `studioDatabase` for
|
|
72
|
-
server-side tooling flows. Use it for tables, rows, controlled SQL, migrations,
|
|
73
|
-
sync, and backup. Do not import it into browser/client bundles. Do not put
|
|
74
|
-
schema creation or migration logic in normal project runtime request handlers;
|
|
75
|
-
run those operations from LICOS agent/tooling flows before the app starts.
|
|
71
|
+
Studio project database management is exposed through `studioDatabase` for
|
|
72
|
+
server-side tooling flows. Use it for tables, rows, controlled SQL, migrations,
|
|
73
|
+
sync, and backup. Do not import it into browser/client bundles. Do not put
|
|
74
|
+
schema creation or migration logic in normal project runtime request handlers;
|
|
75
|
+
run those operations from LICOS agent/tooling flows before the app starts.
|
|
76
76
|
|
|
77
77
|
```js
|
|
78
78
|
import { studioDatabase } from '@kmlckj/licos-platform-sdk';
|
|
@@ -119,5 +119,58 @@ const results = await knowledge.search('How do I reset my password?', {
|
|
|
119
119
|
});
|
|
120
120
|
```
|
|
121
121
|
|
|
122
|
-
The browser entry does not export knowledge helpers because runtime tokens must
|
|
123
|
-
not be bundled into public frontend code.
|
|
122
|
+
The browser entry does not export knowledge helpers because runtime tokens must
|
|
123
|
+
not be bundled into public frontend code.
|
|
124
|
+
|
|
125
|
+
## OAuth2 Application Management
|
|
126
|
+
|
|
127
|
+
OAuth2 management is available only from trusted Node runtime code. It uses the
|
|
128
|
+
current project owner's platform identity and is not exported by the browser
|
|
129
|
+
entry.
|
|
130
|
+
|
|
131
|
+
```js
|
|
132
|
+
import { oauth } from '@kmlckj/licos-platform-sdk';
|
|
133
|
+
|
|
134
|
+
const apps = await oauth.listApps();
|
|
135
|
+
const app = await oauth.ensureProjectApp({
|
|
136
|
+
appId: apps.list?.[0]?.id,
|
|
137
|
+
name: 'Project login',
|
|
138
|
+
loginAudience: 'ALL',
|
|
139
|
+
redirectUriConfigs: [
|
|
140
|
+
{ environment: 'prod', redirectUri: 'https://app.example/auth/callback' },
|
|
141
|
+
],
|
|
142
|
+
});
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
`ensureProjectApp` requires an explicit login audience and at least one
|
|
146
|
+
callback. Store only public PKCE settings in project configuration; never put
|
|
147
|
+
the returned client secret or a platform user token in browser code.
|
|
148
|
+
|
|
149
|
+
## OAuth2 Project Runtime
|
|
150
|
+
|
|
151
|
+
Project server routes use `oauthRuntime` for Authorization Code + PKCE. The
|
|
152
|
+
runtime module reads `config/licos-oauth.json`; it is intentionally absent from
|
|
153
|
+
the browser entry.
|
|
154
|
+
|
|
155
|
+
```js
|
|
156
|
+
import { oauthRuntime } from '@kmlckj/licos-platform-sdk';
|
|
157
|
+
|
|
158
|
+
const config = await oauthRuntime.loadConfig();
|
|
159
|
+
const attempt = oauthRuntime.createAuthorizationRequest(config, {
|
|
160
|
+
redirectUri: 'https://app.example/api/auth/licos/callback',
|
|
161
|
+
});
|
|
162
|
+
|
|
163
|
+
// Persist a hash of attempt.state plus codeVerifier, redirectUri and expiresAt
|
|
164
|
+
// in a one-time server-side record before redirecting the browser.
|
|
165
|
+
|
|
166
|
+
const completed = await oauthRuntime.completeAuthorization(config, {
|
|
167
|
+
code,
|
|
168
|
+
redirectUri: stored.redirectUri,
|
|
169
|
+
codeVerifier: stored.codeVerifier,
|
|
170
|
+
});
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
`completeAuthorization` returns platform tokens and userinfo to trusted server
|
|
174
|
+
code. Map `completed.user.sub` to the project's account, create the project's
|
|
175
|
+
own session, then revoke tokens unless the application explicitly needs
|
|
176
|
+
delegated platform API access. Never return these tokens to the browser.
|
package/dist/index.d.ts
CHANGED
|
@@ -7,6 +7,186 @@ export class PlatformSdkError extends Error {
|
|
|
7
7
|
export class ConfigurationError extends PlatformSdkError {}
|
|
8
8
|
export class ApiError extends PlatformSdkError {}
|
|
9
9
|
|
|
10
|
+
export interface RuntimeConfig {
|
|
11
|
+
baseUrl: string;
|
|
12
|
+
projectId: string;
|
|
13
|
+
workspaceId?: string;
|
|
14
|
+
userId?: string;
|
|
15
|
+
token?: string;
|
|
16
|
+
environment: string;
|
|
17
|
+
ownerProjectId?: string;
|
|
18
|
+
ownerWorkspaceId?: string;
|
|
19
|
+
ownerOrgId?: string;
|
|
20
|
+
ownerUserId?: string;
|
|
21
|
+
ownerProjectType?: string;
|
|
22
|
+
ownerApplicationType?: string;
|
|
23
|
+
runtimeEnv?: string;
|
|
24
|
+
currentUserId?: string;
|
|
25
|
+
currentUserOrgId?: string;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function runtimeConfig(options?: { environmentOverrideEnv?: string }): Promise<RuntimeConfig>;
|
|
29
|
+
export function authHeaders(config: RuntimeConfig, contentType?: string): Record<string, string>;
|
|
30
|
+
|
|
31
|
+
export type OAuthLoginAudience = 'ALL' | 'OWNER_TENANT';
|
|
32
|
+
|
|
33
|
+
export interface OAuthRedirectUriConfig {
|
|
34
|
+
environment?: 'dev' | 'prod';
|
|
35
|
+
redirectUri: string;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export interface OAuthApp {
|
|
39
|
+
id: string;
|
|
40
|
+
tenantId?: string;
|
|
41
|
+
appCode?: string;
|
|
42
|
+
name?: string;
|
|
43
|
+
description?: string;
|
|
44
|
+
clientId?: string;
|
|
45
|
+
loginAudience?: OAuthLoginAudience;
|
|
46
|
+
redirectUris?: string[];
|
|
47
|
+
redirectUriConfigs?: OAuthRedirectUriConfig[];
|
|
48
|
+
allowedScopes?: string[];
|
|
49
|
+
secret?: string;
|
|
50
|
+
status?: string;
|
|
51
|
+
[key: string]: unknown;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export interface OAuthAppList {
|
|
55
|
+
list?: OAuthApp[];
|
|
56
|
+
total?: number;
|
|
57
|
+
page?: number;
|
|
58
|
+
pageSize?: number;
|
|
59
|
+
hasNext?: boolean;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export interface CreateOAuthAppOptions {
|
|
63
|
+
description?: string;
|
|
64
|
+
appCode?: string;
|
|
65
|
+
app_code?: string;
|
|
66
|
+
loginAudience?: OAuthLoginAudience;
|
|
67
|
+
login_audience?: OAuthLoginAudience;
|
|
68
|
+
redirectUriConfigs?: OAuthRedirectUriConfig[];
|
|
69
|
+
redirect_uri_configs?: OAuthRedirectUriConfig[];
|
|
70
|
+
redirectUris?: string[];
|
|
71
|
+
redirect_uris?: string[];
|
|
72
|
+
allowedScopes?: string[];
|
|
73
|
+
allowed_scopes?: string[];
|
|
74
|
+
appType?: string;
|
|
75
|
+
app_type?: string;
|
|
76
|
+
consentRequired?: boolean;
|
|
77
|
+
consent_required?: boolean;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export interface EnsureProjectOAuthAppOptions extends CreateOAuthAppOptions {
|
|
81
|
+
name: string;
|
|
82
|
+
loginAudience: OAuthLoginAudience;
|
|
83
|
+
appId?: string;
|
|
84
|
+
app_id?: string;
|
|
85
|
+
redirectUriConfigs: OAuthRedirectUriConfig[];
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export function listOAuthApps(options?: { page?: number; pageSize?: number }): Promise<OAuthAppList>;
|
|
89
|
+
export function getOAuthApp(appId: string): Promise<OAuthApp>;
|
|
90
|
+
export function createOAuthApp(name: string, options?: CreateOAuthAppOptions): Promise<OAuthApp>;
|
|
91
|
+
export function updateOAuthApp(appId: string, changes?: Record<string, unknown>): Promise<OAuthApp>;
|
|
92
|
+
export function deleteOAuthApp(appId: string): Promise<void>;
|
|
93
|
+
export function setOAuthAppEnabled(appId: string, enabled: boolean): Promise<OAuthApp>;
|
|
94
|
+
export function rotateOAuthAppSecret(appId: string): Promise<OAuthApp>;
|
|
95
|
+
export function listOAuthGrants(appId: string): Promise<Array<Record<string, unknown>>>;
|
|
96
|
+
export function revokeOAuthGrant(grantId: string): Promise<void>;
|
|
97
|
+
export function findOAuthAppByCode(appCode: string, options?: { pageSize?: number }): Promise<OAuthApp | null>;
|
|
98
|
+
export function ensureProjectOAuthApp(options: EnsureProjectOAuthAppOptions): Promise<OAuthApp>;
|
|
99
|
+
|
|
100
|
+
export const oauth: {
|
|
101
|
+
listApps: typeof listOAuthApps;
|
|
102
|
+
getApp: typeof getOAuthApp;
|
|
103
|
+
createApp: typeof createOAuthApp;
|
|
104
|
+
updateApp: typeof updateOAuthApp;
|
|
105
|
+
deleteApp: typeof deleteOAuthApp;
|
|
106
|
+
setEnabled: typeof setOAuthAppEnabled;
|
|
107
|
+
rotateSecret: typeof rotateOAuthAppSecret;
|
|
108
|
+
listGrants: typeof listOAuthGrants;
|
|
109
|
+
revokeGrant: typeof revokeOAuthGrant;
|
|
110
|
+
findAppByCode: typeof findOAuthAppByCode;
|
|
111
|
+
ensureProjectApp: typeof ensureProjectOAuthApp;
|
|
112
|
+
};
|
|
113
|
+
|
|
114
|
+
export class OAuthProtocolError extends ApiError {
|
|
115
|
+
error?: string;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
export interface OAuthRuntimeConfig {
|
|
119
|
+
clientId: string;
|
|
120
|
+
publicBaseUrl: string;
|
|
121
|
+
scopes: readonly string[];
|
|
122
|
+
redirectUris: readonly string[];
|
|
123
|
+
endpoints: Readonly<Record<string, string>>;
|
|
124
|
+
appId?: string;
|
|
125
|
+
appCode?: string;
|
|
126
|
+
loginAudience?: OAuthLoginAudience;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
export interface OAuthAuthorizationRequest {
|
|
130
|
+
authorizationUrl: string;
|
|
131
|
+
state: string;
|
|
132
|
+
codeVerifier: string;
|
|
133
|
+
redirectUri: string;
|
|
134
|
+
expiresAt: number;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
export interface OAuthTokenResponse {
|
|
138
|
+
access_token: string;
|
|
139
|
+
token_type?: string;
|
|
140
|
+
expires_in?: number;
|
|
141
|
+
refresh_token?: string;
|
|
142
|
+
scope?: string;
|
|
143
|
+
id_token?: string;
|
|
144
|
+
[key: string]: unknown;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
export function loadOAuthRuntimeConfig(options?: { configPath?: string }): Promise<OAuthRuntimeConfig>;
|
|
148
|
+
export function createOAuthAuthorizationRequest(
|
|
149
|
+
config: OAuthRuntimeConfig,
|
|
150
|
+
options: {
|
|
151
|
+
redirectUri: string;
|
|
152
|
+
scopes?: string[];
|
|
153
|
+
state?: string;
|
|
154
|
+
codeVerifier?: string;
|
|
155
|
+
ttlSeconds?: number;
|
|
156
|
+
now?: number;
|
|
157
|
+
},
|
|
158
|
+
): OAuthAuthorizationRequest;
|
|
159
|
+
export function exchangeOAuthAuthorizationCode(
|
|
160
|
+
config: OAuthRuntimeConfig,
|
|
161
|
+
options: { code: string; redirectUri: string; codeVerifier: string },
|
|
162
|
+
): Promise<OAuthTokenResponse>;
|
|
163
|
+
export function refreshOAuthAccessToken(
|
|
164
|
+
config: OAuthRuntimeConfig,
|
|
165
|
+
options: { refreshToken: string; scopes?: string[] },
|
|
166
|
+
): Promise<OAuthTokenResponse>;
|
|
167
|
+
export function getOAuthUserInfo(
|
|
168
|
+
config: OAuthRuntimeConfig,
|
|
169
|
+
options: { accessToken: string },
|
|
170
|
+
): Promise<Record<string, unknown>>;
|
|
171
|
+
export function revokeOAuthToken(
|
|
172
|
+
config: OAuthRuntimeConfig,
|
|
173
|
+
options: { token: string; tokenTypeHint?: 'access_token' | 'refresh_token' | string },
|
|
174
|
+
): Promise<void>;
|
|
175
|
+
export function completeOAuthAuthorization(
|
|
176
|
+
config: OAuthRuntimeConfig,
|
|
177
|
+
options: { code: string; redirectUri: string; codeVerifier: string },
|
|
178
|
+
): Promise<{ tokens: OAuthTokenResponse; user: Record<string, unknown> }>;
|
|
179
|
+
|
|
180
|
+
export const oauthRuntime: {
|
|
181
|
+
loadConfig: typeof loadOAuthRuntimeConfig;
|
|
182
|
+
createAuthorizationRequest: typeof createOAuthAuthorizationRequest;
|
|
183
|
+
exchangeAuthorizationCode: typeof exchangeOAuthAuthorizationCode;
|
|
184
|
+
refreshAccessToken: typeof refreshOAuthAccessToken;
|
|
185
|
+
getUserInfo: typeof getOAuthUserInfo;
|
|
186
|
+
revokeToken: typeof revokeOAuthToken;
|
|
187
|
+
completeAuthorization: typeof completeOAuthAuthorization;
|
|
188
|
+
};
|
|
189
|
+
|
|
10
190
|
export const DataSourceType: {
|
|
11
191
|
TEXT: 0;
|
|
12
192
|
URL: 1;
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export{PlatformSdkError,ConfigurationError,ApiError}from"./shared.js";export*from"./database.js";export*from"./knowledge.js";export*from"./storage.js";export{studioDatabase}from"./studio-database.js";
|
|
1
|
+
export{PlatformSdkError,ConfigurationError,ApiError}from"./shared.js";export{runtimeConfig,authHeaders}from"./runtime.js";export*from"./database.js";export*from"./knowledge.js";export*from"./oauth.js";export*from"./oauth-runtime.js";export*from"./storage.js";export{studioDatabase}from"./studio-database.js";
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createHash as e,randomBytes as t}from"node:crypto";import{readFile as r}from"node:fs/promises";import o from"node:path";import{ApiError as n}from"./shared.js";const i=["authorization","token","userinfo","revoke"],s=/^[A-Za-z0-9._~-]{43,128}$/;export class OAuthProtocolError extends n{constructor(e,t={}){super(e,t),this.error=t.error}}function c(e,t){const r=String(e||"").trim();let o;try{o=new URL(r)}catch{throw new TypeError(`${t} must be an absolute http(s) URL`)}if(!["http:","https:"].includes(o.protocol))throw new TypeError(`${t} must be an absolute http(s) URL`);if(o.hash)throw new TypeError(`${t} must not contain a fragment`);return r}function a(e){return new URL(e).origin.toLowerCase()}function u(e,t,r){const o=String(t||"").trim();if(!o)throw new TypeError(`OAuth endpoint is missing: ${r}`);const n=c(new URL(o,`${e}/`).toString(),`endpoints.${r}`);if(a(n)!==a(e))throw new TypeError(`OAuth endpoint ${r} must use the same origin as publicBaseUrl`);return n}function h(e){return!(!e||"object"!=typeof e)&&(Array.isArray(e)?e.some(h):Object.entries(e).some(([e,t])=>e.toLowerCase().replaceAll("_","").includes("secret")||h(t)))}export async function loadOAuthRuntimeConfig({configPath:e}={}){const t=o.resolve(process.env.LICOS_PROJECT_PATH||process.cwd()),n=o.resolve(e||o.join(t,"config/licos-oauth.json"));let s;try{s=JSON.parse(await r(n,"utf8"))}catch(e){if("ENOENT"===e?.code)throw new TypeError(`OAuth config not found: ${n}`);if(e instanceof SyntaxError)throw new TypeError(`OAuth config is not valid JSON: ${n}`);throw e}if(!s||"object"!=typeof s||Array.isArray(s))throw new TypeError("OAuth config must be a JSON object");if(h(s))throw new TypeError("OAuth config must not contain client secret fields");if("licos-oauth2"!==s.provider)throw new TypeError("OAuth config provider must be licos-oauth2");if(!0!==s.pkce)throw new TypeError("OAuth config must enable PKCE");const a=String(s.clientId||"").trim();if(!a)throw new TypeError("OAuth config is missing clientId");const p=c(s.publicBaseUrl,"publicBaseUrl").replace(/\/$/,"");if(!Array.isArray(s.scopes)||0===s.scopes.length||s.scopes.some(e=>!String(e).trim()))throw new TypeError("OAuth config scopes must be a non-empty string array");if(!Array.isArray(s.redirectUriConfigs)||0===s.redirectUriConfigs.length)throw new TypeError("OAuth config redirectUriConfigs must not be empty");const f=[...new Set(s.scopes.map(e=>String(e).trim()))],d=[...new Set(s.redirectUriConfigs.map(e=>c(e?.redirectUri,"redirectUri")))];if(!s.endpoints||"object"!=typeof s.endpoints||Array.isArray(s.endpoints))throw new TypeError("OAuth config endpoints must be an object");const l=Object.fromEntries(Object.entries(s.endpoints).map(([e,t])=>[e,u(p,t,e)]));for(const e of i)if(!l[e])throw new TypeError(`OAuth endpoint is missing: ${e}`);return Object.freeze({clientId:a,publicBaseUrl:p,scopes:Object.freeze(f),redirectUris:Object.freeze(d),endpoints:Object.freeze(l),appId:String(s.appId||"").trim()||void 0,appCode:String(s.appCode||"").trim()||void 0,loginAudience:String(s.loginAudience||"").trim()||void 0})}function p(e,t){const r=c(t,"redirectUri");if(!e.redirectUris.includes(r))throw new TypeError("redirectUri is not configured for this OAuth application");return r}function f(e){if(!s.test(e))throw new TypeError("codeVerifier must be 43-128 RFC 7636 unreserved characters");return e}function d(e,t){const r=[...new Set((t||e.scopes).map(e=>String(e).trim()).filter(Boolean))];if(0===r.length)throw new TypeError("at least one OAuth scope is required");const o=r.filter(t=>!e.scopes.includes(t));if(o.length)throw new TypeError(`OAuth scopes are not configured: ${o.sort().join(", ")}`);return r}export function createOAuthAuthorizationRequest(r,o){const n=p(r,o?.redirectUri),i=d(r,o?.scopes),s=String(o?.state||t(32).toString("base64url")).trim();if(!s)throw new TypeError("state is required");const c=f(o?.codeVerifier||t(64).toString("base64url")),a=o?.ttlSeconds??600;if(!Number.isInteger(a)||a<=0)throw new TypeError("ttlSeconds must be a positive integer");const u=e("sha256").update(c,"ascii").digest("base64url"),h=new URL(r.endpoints.authorization);h.search=new URLSearchParams({response_type:"code",client_id:r.clientId,redirect_uri:n,scope:i.join(" "),state:s,code_challenge:u,code_challenge_method:"S256"}).toString();const l=o?.now??Math.floor(Date.now()/1e3);return{authorizationUrl:h.toString(),state:s,codeVerifier:c,redirectUri:n,expiresAt:l+a}}function l(e,t){let r;try{r=e?JSON.parse(e):void 0}catch{r=void 0}const o=r&&"object"==typeof r&&String(r.error||"").trim()||void 0,n=r&&"object"==typeof r&&(r.error_description||r.message||o)||e||"OAuth request failed";return new OAuthProtocolError(String(n),{status:t,error:o,details:r})}async function w(e,{method:t,form:r,accessToken:o,allowEmpty:n=!1}){const i={Accept:"application/json"};let s,c;r&&(s=new URLSearchParams(Object.entries(r).filter(([,e])=>null!=e)).toString(),i["Content-Type"]="application/x-www-form-urlencoded"),o&&(i.Authorization=`Bearer ${o}`);try{c=await fetch(e,{method:t,headers:i,body:s})}catch(e){throw new OAuthProtocolError(`OAuth request failed: ${e?.message||e}`)}const a=await c.text();if(!c.ok)throw l(a,c.status);if(!a){if(n)return;throw new OAuthProtocolError("OAuth response body is empty",{status:c.status})}let u;try{u=JSON.parse(a)}catch{throw new OAuthProtocolError("OAuth response is not valid JSON",{status:c.status})}if(!u||"object"!=typeof u||Array.isArray(u))throw new OAuthProtocolError("OAuth response is not an object",{status:c.status,details:u});if(u.error)throw l(a,c.status);return u}export async function exchangeOAuthAuthorizationCode(e,t){const r=String(t?.code||"").trim();if(!r)throw new TypeError("authorization code is required");const o=p(e,t?.redirectUri),n=f(t?.codeVerifier);return w(e.endpoints.token,{method:"POST",form:{grant_type:"authorization_code",client_id:e.clientId,code:r,redirect_uri:o,code_verifier:n}})}export async function refreshOAuthAccessToken(e,t){const r=String(t?.refreshToken||"").trim();if(!r)throw new TypeError("refreshToken is required");return w(e.endpoints.token,{method:"POST",form:{grant_type:"refresh_token",client_id:e.clientId,refresh_token:r,scope:t?.scopes?d(e,t.scopes).join(" "):void 0}})}export async function getOAuthUserInfo(e,t){const r=String(t?.accessToken||"").trim();if(!r)throw new TypeError("accessToken is required");return w(e.endpoints.userinfo,{method:"GET",accessToken:r})}export async function revokeOAuthToken(e,t){const r=String(t?.token||"").trim();if(!r)throw new TypeError("token is required");await w(e.endpoints.revoke,{method:"POST",form:{client_id:e.clientId,token:r,token_type_hint:t?.tokenTypeHint},allowEmpty:!0})}export async function completeOAuthAuthorization(e,t){const r=await exchangeOAuthAuthorizationCode(e,t),o=String(r.access_token||"").trim();if(!o)throw new OAuthProtocolError("OAuth token response is missing access_token",{details:r});return{tokens:r,user:await getOAuthUserInfo(e,{accessToken:o})}}export const oauthRuntime={loadConfig:loadOAuthRuntimeConfig,createAuthorizationRequest:createOAuthAuthorizationRequest,exchangeAuthorizationCode:exchangeOAuthAuthorizationCode,refreshAccessToken:refreshOAuthAccessToken,getUserInfo:getOAuthUserInfo,revokeToken:revokeOAuthToken,completeAuthorization:completeOAuthAuthorization};
|
package/dist/oauth.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{ApiError as e,ConfigurationError as t}from"./shared.js";import{authHeaders as n,refreshRuntimeConfig as o,runtimeConfig as r,shouldRefreshUserToken as i}from"./runtime.js";const p=Object.freeze({integration_type:"integrationType",app_code:"appCode",logo_url:"logoUrl",app_type:"appType",consent_required:"consentRequired",login_audience:"loginAudience",redirect_uris:"redirectUris",redirect_uri_configs:"redirectUriConfigs",allowed_scopes:"allowedScopes",sso_ticket_ttl_seconds:"ssoTicketTtlSeconds",sso_silent_enabled:"ssoSilentEnabled",allowed_workspace_scope:"allowedWorkspaceScope"});function a(e,t,n={}){const o=new URL(`${e.baseUrl}/api/v1/admin/login-integrations${t}`);for(const[e,t]of Object.entries(n))null!=t&&o.searchParams.set(e,String(t));return o}async function s(t){const n=await t.text(),o=n?JSON.parse(n):null;if(!t.ok)throw new e(o?.message||n||`platform OAuth2 API returned ${t.status}`,{status:t.status,code:"number"==typeof o?.code?o.code:void 0,details:o});if(!o||"object"!=typeof o)return o;if(void 0!==o.code&&0!==o.code||!1===o.success)throw new e(o.message||"platform OAuth2 API failed",{status:t.status,code:"number"==typeof o.code?o.code:void 0,details:o});return o.data}async function c(t,p,{params:c,body:d}={}){let u=await r();for(let e=0;e<2;e+=1)try{const e=await fetch(a(u,p,c),{method:t,headers:n(u),body:void 0===d?void 0:JSON.stringify(d)});return await s(e)}catch(t){if(0===e&&i(t)){u=await o(u);continue}throw t}throw new e("platform OAuth2 API failed")}export async function listOAuthApps({page:e=1,pageSize:t=100}={}){return c("GET","/apps",{params:{page:e,pageSize:t}})}export async function getOAuthApp(e){return c("GET",`/apps/${encodeURIComponent(e)}`)}export async function createOAuthApp(e,t={}){return c("POST","/apps",{body:(n={name:e,description:t.description,appCode:t.appCode??t.app_code,loginAudience:t.loginAudience??t.login_audience??"ALL",redirectUriConfigs:t.redirectUriConfigs??t.redirect_uri_configs,redirectUris:t.redirectUris??t.redirect_uris,allowedScopes:t.allowedScopes??t.allowed_scopes,appType:t.appType??t.app_type,consentRequired:t.consentRequired??t.consent_required},Object.fromEntries(Object.entries(n).filter(([,e])=>null!=e)))});var n}export async function updateOAuthApp(e,t={}){const n=Object.fromEntries(Object.entries(t).map(([e,t])=>[p[e]||e,t]));return c("PUT",`/apps/${encodeURIComponent(e)}`,{body:n})}export async function deleteOAuthApp(e){await c("DELETE",`/apps/${encodeURIComponent(e)}`)}export async function setOAuthAppEnabled(e,t){return c("POST",`/apps/${encodeURIComponent(e)}/${t?"enable":"disable"}`)}export async function rotateOAuthAppSecret(e){return c("POST",`/apps/${encodeURIComponent(e)}/secrets/rotate`)}export async function listOAuthGrants(e){return await c("GET",`/apps/${encodeURIComponent(e)}/grants`)||[]}export async function revokeOAuthGrant(e){await c("DELETE",`/grants/${encodeURIComponent(e)}`)}export async function findOAuthAppByCode(e,{pageSize:t=100}={}){let n=1;for(;;){const o=await listOAuthApps({page:n,pageSize:t})||{},r=(o.list||[]).find(t=>t.appCode===e);if(r)return r;if(!o.hasNext)return null;n+=1}}export async function ensureProjectOAuthApp(e){if(!e||"object"!=typeof e)throw new t("OAuth project app options are required");if(!String(e.name||"").trim())throw new t("name is required");const n=e.loginAudience??e.login_audience;if(!["ALL","OWNER_TENANT"].includes(n))throw new t("loginAudience must be ALL or OWNER_TENANT");const o=e.redirectUriConfigs??e.redirect_uri_configs;if(!Array.isArray(o)||0===o.length)throw new t("redirectUriConfigs must contain at least one callback");if(o.some(e=>!String(e?.redirectUri||"").trim()))throw new t("every redirectUriConfigs item requires redirectUri");const i={name:e.name,login_audience:n,redirect_uri_configs:o,allowed_scopes:e.allowedScopes??e.allowed_scopes??["openid","profile","email"]};if(void 0!==e.description&&null!==e.description&&(i.description=e.description),e.appId??e.app_id){const t=e.appId??e.app_id;return await getOAuthApp(t),updateOAuthApp(t,i)}const p=`project-${(await r()).projectId}`,a=await findOAuthAppByCode(p);return a?updateOAuthApp(a.id,i):createOAuthApp(e.name,{description:e.description,appCode:p,loginAudience:i.login_audience,redirectUriConfigs:i.redirect_uri_configs,allowedScopes:i.allowed_scopes})}export const oauth={listApps:listOAuthApps,getApp:getOAuthApp,createApp:createOAuthApp,updateApp:updateOAuthApp,deleteApp:deleteOAuthApp,setEnabled:setOAuthAppEnabled,rotateSecret:rotateOAuthAppSecret,listGrants:listOAuthGrants,revokeGrant:revokeOAuthGrant,findAppByCode:findOAuthAppByCode,ensureProjectApp:ensureProjectOAuthApp};
|
package/dist/runtime.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ConfigurationError as e}from"./shared.js";const
|
|
1
|
+
import{ConfigurationError as e}from"./shared.js";const r=new Map;export function env(e){const r=process.env[e];if("string"!=typeof r)return;return r.trim()||void 0}function n(e,r,n){const t=env(e);if(t)return`http://${t}:${env(r)||n}`}export function platformBaseUrl(){const r=env("LICOS_PLATFORM_API_BASE_URL")||n("AIOS_PLATFORM_SERVICE_HOST","AIOS_PLATFORM_SERVICE_PORT","9100")||n("LICOS_PLATFORM_SERVICE_HOST","LICOS_PLATFORM_SERVICE_PORT","9100")||n("PLATFORM_SERVICE_HOST","PLATFORM_SERVICE_PORT","9100");if(!r)throw new e("LICOS_PLATFORM_API_BASE_URL is not configured");return function(e){let r=e.trim().replace(/\/+$/,"");return r.endsWith("/api/v1")&&(r=r.slice(0,-7)),r.replace(/\/+$/,"")}(r)}export function projectEnvironment(e){const r=((e?env(e):void 0)||"").toLowerCase();if("dev"===r||"prod"===r)return r;const n=(env("LICOS_PROJECT_ENV")||env("AGENT_ENV")||"").toLowerCase();return["prod","production","release"].includes(n)?"prod":"dev"}async function t(n,t,{forceRefresh:o=!1}={}){const s=String(t||"").trim();if(!s)throw new e("project owner user ID is not configured");const c=env("LICOS_AI_AGENT_TOKEN");if(!c)throw new e("platform runtime identity is unavailable");const i=`${n}\n${s}\n${c}`;if(r.has(i)){const e=r.get(i);if(!o)return e;if(e&&"function"==typeof e.then)return e}const I=fetch(`${n}/api/v1/internal/auth/ai-user-token`,{method:"POST",headers:{Authorization:`Bearer ${c}`,"Content-Type":"application/json"},body:JSON.stringify({userId:s})}).then(async n=>{const t=await n.text();let o=null;try{o=t?JSON.parse(t):null}catch(r){const o=new e("parse AI user token exchange response failed");throw o.status=n.status,o.details=t,o}if(!n.ok){const r=o?.message||t||`AI user token exchange returned ${n.status}`,s=new e(r);throw s.status=n.status,s.details=o,s}const s=function(r){if(!r||"object"!=typeof r)throw new e("AI user token exchange response is not an object");if(void 0!==r.code&&0!==r.code||!1===r.success){const n=new e(r.message||"AI user token exchange failed");throw n.code="number"==typeof r.code?r.code:void 0,n.details=r,n}const n=r.data,t="string"==typeof n?n.trim():String(n?.accessToken||n?.access_token||n?.token||"").trim();if(!t){const n=new e("AI user token exchange response missing accessToken");throw n.details=r,n}return t}(o);return r.set(i,s),s});r.set(i,I);try{return await I}catch(e){throw r.delete(i),e}}export function clearTokenCacheForTests(){r.clear()}export function shouldRefreshUserToken(e){return 401===e?.status||10002===e?.code}export async function refreshRuntimeConfig(e){return{...e,token:await t(e.baseUrl,e.userId,{forceRefresh:!0})}}export async function runtimeConfig({environmentOverrideEnv:r}={}){const n=env("LICOS_OWNER_PROJECT_ID"),o=env("LICOS_OWNER_WORKSPACE_ID"),s=env("LICOS_OWNER_USER_ID"),c=env("LICOS_PROJECT_ID")||n||env("AGENT_PROJECT_ID");if(!c)throw new e("LICOS_PROJECT_ID or AGENT_PROJECT_ID is not configured");const i=platformBaseUrl(),I=env("LICOS_USER_ID")||s||env("AGENT_USER_ID"),a=await t(i,I);return{baseUrl:i,projectId:c,environment:projectEnvironment(r),token:a,workspaceId:env("LICOS_WORKSPACE_ID")||o||env("AGENT_WORKSPACE_ID"),userId:I,ownerProjectId:n||c,ownerWorkspaceId:o,ownerOrgId:env("LICOS_OWNER_ORG_ID"),ownerUserId:s||I,ownerProjectType:env("LICOS_OWNER_PROJECT_TYPE"),ownerApplicationType:env("LICOS_OWNER_APPLICATION_TYPE"),runtimeEnv:env("LICOS_RUNTIME_ENV"),currentUserId:env("LICOS_CURRENT_USER_ID"),currentUserOrgId:env("LICOS_CURRENT_USER_ORG_ID")}}export function authHeaders(e,r="application/json"){const n={Authorization:`Bearer ${e.token}`};return r&&(n["Content-Type"]=r),e.workspaceId&&(n["X-Workspace-Id"]=e.workspaceId),e.userId&&(n["X-User-Id"]=e.userId),o(n,"X-Licos-Current-User-Id",e.currentUserId),o(n,"X-Licos-Current-Org-Id",e.currentUserOrgId),o(n,"current_user_id",e.currentUserId),o(n,"current_user_org_id",e.currentUserOrgId),o(n,"X-Licos-Runtime-Env",e.runtimeEnv),o(n,"X-Runtime-Env",e.runtimeEnv),o(n,"runtime_env",e.runtimeEnv),o(n,"owner_project_type",e.ownerProjectType),o(n,"owner_application_type",e.ownerApplicationType),e.ownerProjectId&&(o(n,"X-Licos-Owner-Project-Id",e.ownerProjectId),o(n,"X-Licos-Owner-Workspace-Id",e.ownerWorkspaceId),o(n,"X-Licos-Owner-Org-Id",e.ownerOrgId),o(n,"X-Licos-Owner-User-Id",e.ownerUserId),o(n,"owner_project_id",e.ownerProjectId),o(n,"owner_workspace_id",e.ownerWorkspaceId),o(n,"owner_org_id",e.ownerOrgId),o(n,"owner_user_id",e.ownerUserId),o(n,"X-Project-Id",e.ownerProjectId),o(n,"X-Workspace-Id",e.ownerWorkspaceId),o(n,"X-Tenant-Id",e.ownerOrgId),o(n,"X-User-Id",e.ownerUserId)),n}function o(e,r,n){if("string"!=typeof n)return;const t=n.trim();t&&(e[r]=t)}
|