@zjazj/server 0.0.7 → 0.0.9
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/dist/api-keys-R2145cd9.d.ts +208 -0
- package/dist/{chunk-EIZ24ILA.js → chunk-44UTXMKV.js} +20 -4
- package/dist/{chunk-NMKEVYGN.js → chunk-SLNRMJDM.js} +20 -1
- package/dist/chunk-UWTSXBJL.js +345 -0
- package/dist/{chunk-26AAYRI3.js → chunk-VJRJ53T2.js} +1 -0
- package/dist/db.js +3 -1
- package/dist/dev.d.ts +18 -2
- package/dist/dev.js +7 -1
- package/dist/index.d.ts +249 -10
- package/dist/index.js +397 -10
- package/dist/log.js +1 -1
- package/dist/mcp-4RD7G65J.js +139 -0
- package/dist/testing.d.ts +29 -2
- package/dist/testing.js +64 -4
- package/package.json +5 -2
- package/dist/auth-Ckmm4C6y.d.ts +0 -81
- package/dist/chunk-UWDDQH25.js +0 -146
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import {
|
|
2
|
+
log
|
|
3
|
+
} from "./chunk-VJRJ53T2.js";
|
|
4
|
+
import {
|
|
5
|
+
bearerToken,
|
|
6
|
+
getUser,
|
|
7
|
+
hasPermissions
|
|
8
|
+
} from "./chunk-44UTXMKV.js";
|
|
9
|
+
import {
|
|
10
|
+
AppError
|
|
11
|
+
} from "./chunk-UWTSXBJL.js";
|
|
12
|
+
import "./chunk-SLNRMJDM.js";
|
|
13
|
+
import {
|
|
14
|
+
getRequestId
|
|
15
|
+
} from "./chunk-ERGI2X5S.js";
|
|
16
|
+
|
|
17
|
+
// src/mcp.ts
|
|
18
|
+
import {
|
|
19
|
+
createMcpHandler,
|
|
20
|
+
McpServer,
|
|
21
|
+
originValidationResponse
|
|
22
|
+
} from "@modelcontextprotocol/server";
|
|
23
|
+
var CONTEXT = "platformContext";
|
|
24
|
+
function contextOf(request) {
|
|
25
|
+
const c = request.authInfo?.extra?.[CONTEXT];
|
|
26
|
+
if (!c) throw new Error("The MCP endpoint was called without its request context");
|
|
27
|
+
return c;
|
|
28
|
+
}
|
|
29
|
+
function toResult(value) {
|
|
30
|
+
if (typeof value === "string") return { content: [{ type: "text", text: value }] };
|
|
31
|
+
if (value === void 0 || value === null) return { content: [{ type: "text", text: "Done." }] };
|
|
32
|
+
const text = JSON.stringify(value);
|
|
33
|
+
if (typeof value === "object" && !Array.isArray(value)) {
|
|
34
|
+
return {
|
|
35
|
+
content: [{ type: "text", text }],
|
|
36
|
+
structuredContent: value
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
return { content: [{ type: "text", text }] };
|
|
40
|
+
}
|
|
41
|
+
function failure(tool, error) {
|
|
42
|
+
if (error instanceof AppError) {
|
|
43
|
+
log.info("Tool call refused", { tool, code: error.code, status: error.status });
|
|
44
|
+
return { content: [{ type: "text", text: `${error.code}: ${error.message}` }], isError: true };
|
|
45
|
+
}
|
|
46
|
+
log.error("Tool call failed", { tool, err: error });
|
|
47
|
+
return {
|
|
48
|
+
content: [
|
|
49
|
+
{
|
|
50
|
+
type: "text",
|
|
51
|
+
text: `internal_error: The tool failed. Trace ${getRequestId() ?? ""}`.trim()
|
|
52
|
+
}
|
|
53
|
+
],
|
|
54
|
+
isError: true
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
function createMcpRoute(options) {
|
|
58
|
+
const { manifest, tools } = options;
|
|
59
|
+
const inTenant = async (c, work) => {
|
|
60
|
+
if (!options.database) return work();
|
|
61
|
+
const { withTenant } = await import("./db.js");
|
|
62
|
+
return withTenant(await options.database(), getUser(c).tenantId, async (tx) => {
|
|
63
|
+
c.set("db", tx);
|
|
64
|
+
return work();
|
|
65
|
+
});
|
|
66
|
+
};
|
|
67
|
+
const serverFor = (request) => {
|
|
68
|
+
const c = contextOf(request);
|
|
69
|
+
const user = getUser(c);
|
|
70
|
+
const server = new McpServer(
|
|
71
|
+
{
|
|
72
|
+
name: manifest.name,
|
|
73
|
+
title: manifest.platform?.title ?? manifest.name,
|
|
74
|
+
version: manifest.version ?? "0.0.0"
|
|
75
|
+
},
|
|
76
|
+
// What a caller is shown depends on the caller's permissions.
|
|
77
|
+
{ cacheHints: { "tools/list": { ttlMs: 0, cacheScope: "private" } } }
|
|
78
|
+
);
|
|
79
|
+
for (const tool of tools) {
|
|
80
|
+
const registered = server.registerTool(
|
|
81
|
+
tool.name,
|
|
82
|
+
{
|
|
83
|
+
...tool.title ? { title: tool.title } : {},
|
|
84
|
+
description: tool.description,
|
|
85
|
+
inputSchema: tool.input,
|
|
86
|
+
...tool.output ? { outputSchema: tool.output } : {},
|
|
87
|
+
annotations: { ...tool.title ? { title: tool.title } : {}, ...tool.annotations }
|
|
88
|
+
},
|
|
89
|
+
async (input) => {
|
|
90
|
+
try {
|
|
91
|
+
if (!hasPermissions(getUser(c).permissions, [tool.permission])) {
|
|
92
|
+
throw new AppError(`requires permission: ${tool.permission}`, {
|
|
93
|
+
code: "insufficient_permission",
|
|
94
|
+
status: 403
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
const result = toResult(await inTenant(c, () => tool.handler(c, input)));
|
|
98
|
+
log.info("Tool call", { tool: tool.name });
|
|
99
|
+
return result;
|
|
100
|
+
} catch (error) {
|
|
101
|
+
return failure(tool.name, error);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
);
|
|
105
|
+
if (!hasPermissions(user.permissions, [tool.permission])) registered.remove();
|
|
106
|
+
}
|
|
107
|
+
return server;
|
|
108
|
+
};
|
|
109
|
+
let handler;
|
|
110
|
+
return async (c) => {
|
|
111
|
+
const refused = originValidationResponse(c.req.raw, [new URL(c.req.url).hostname]);
|
|
112
|
+
if (refused) return refused;
|
|
113
|
+
if (!handler) {
|
|
114
|
+
const warn = console.warn;
|
|
115
|
+
console.warn = () => {
|
|
116
|
+
};
|
|
117
|
+
try {
|
|
118
|
+
handler = createMcpHandler(serverFor, {
|
|
119
|
+
responseMode: "json",
|
|
120
|
+
onerror: (error) => log.warn("MCP request refused", { err: error })
|
|
121
|
+
});
|
|
122
|
+
} finally {
|
|
123
|
+
console.warn = warn;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
const user = getUser(c);
|
|
127
|
+
return handler.fetch(c.req.raw, {
|
|
128
|
+
authInfo: {
|
|
129
|
+
token: bearerToken(c.req.header("Authorization")) ?? "",
|
|
130
|
+
clientId: user.id,
|
|
131
|
+
scopes: user.permissions,
|
|
132
|
+
extra: { [CONTEXT]: c }
|
|
133
|
+
}
|
|
134
|
+
});
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
export {
|
|
138
|
+
createMcpRoute
|
|
139
|
+
};
|
package/dist/testing.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { V as Verifier } from './
|
|
1
|
+
import { V as Verifier, f as ApiKeyVerification, K as KeyVerifier } from './api-keys-R2145cd9.js';
|
|
2
2
|
import 'hono';
|
|
3
3
|
import 'jose';
|
|
4
4
|
|
|
@@ -22,5 +22,32 @@ declare const TEST_TENANT_ID = "0190a000-0000-7000-8000-0000000000a1";
|
|
|
22
22
|
* network call.
|
|
23
23
|
*/
|
|
24
24
|
declare function createTestIssuer(issuer?: string): Promise<TestIssuer>;
|
|
25
|
+
/**
|
|
26
|
+
* A key verifier that knows only the keys given, for tests that run without the dev
|
|
27
|
+
* identity: pass it to `createApp({ keyVerifier })` and call with `Bearer <key>`. Each key
|
|
28
|
+
* starts with `pk_` and maps to the parts of the control plane's answer that differ from
|
|
29
|
+
* a user key of `TEST_TENANT_ID` with no roles and no permissions. Any other key is
|
|
30
|
+
* refused with 401 `invalid_key`. Nothing is kept, so each request asks again.
|
|
31
|
+
*
|
|
32
|
+
* ```ts
|
|
33
|
+
* const keyVerifier = createTestKeyVerifier({
|
|
34
|
+
* pk_test_reader: { permissions: ['stock:item:read'] },
|
|
35
|
+
* pk_test_tenant: { kind: 'tenant', roles: ['sync'], permissions: ['stock:item:write'] },
|
|
36
|
+
* })
|
|
37
|
+
* ```
|
|
38
|
+
*/
|
|
39
|
+
declare function createTestKeyVerifier(keys: Record<string, Partial<ApiKeyVerification>>): KeyVerifier;
|
|
40
|
+
/** The MCP revision `mcpRequest` speaks. */
|
|
41
|
+
declare const MCP_PROTOCOL_VERSION = "2026-07-28";
|
|
42
|
+
/**
|
|
43
|
+
* One request to an app's MCP endpoint, as a client of MCP 2026-07-28 sends it: the
|
|
44
|
+
* method and its name in headers, the revision and the client's capabilities in `_meta`.
|
|
45
|
+
* `token` is sent as `Authorization: Bearer`: a token, a dev token or an API key, as an
|
|
46
|
+
* agent sends its key. Read the answer with `await response.json()`: `result` or `error`.
|
|
47
|
+
*/
|
|
48
|
+
declare function mcpRequest(url: string, method: string, params?: Record<string, unknown>, init?: {
|
|
49
|
+
token?: string;
|
|
50
|
+
headers?: Record<string, string>;
|
|
51
|
+
}): Request;
|
|
25
52
|
|
|
26
|
-
export { type SignOptions, TEST_TENANT_ID, type TestIssuer, createTestIssuer };
|
|
53
|
+
export { MCP_PROTOCOL_VERSION, type SignOptions, TEST_TENANT_ID, type TestIssuer, createTestIssuer, createTestKeyVerifier, mcpRequest };
|
package/dist/testing.js
CHANGED
|
@@ -1,8 +1,11 @@
|
|
|
1
1
|
import {
|
|
2
2
|
createVerifier
|
|
3
|
-
} from "./chunk-
|
|
4
|
-
import
|
|
5
|
-
|
|
3
|
+
} from "./chunk-44UTXMKV.js";
|
|
4
|
+
import {
|
|
5
|
+
createKeyVerifier,
|
|
6
|
+
isApiKey
|
|
7
|
+
} from "./chunk-UWTSXBJL.js";
|
|
8
|
+
import "./chunk-SLNRMJDM.js";
|
|
6
9
|
import "./chunk-ERGI2X5S.js";
|
|
7
10
|
|
|
8
11
|
// src/testing.ts
|
|
@@ -35,7 +38,64 @@ async function createTestIssuer(issuer = "https://auth.test/oidc") {
|
|
|
35
38
|
}
|
|
36
39
|
};
|
|
37
40
|
}
|
|
41
|
+
function createTestKeyVerifier(keys) {
|
|
42
|
+
for (const key of Object.keys(keys)) {
|
|
43
|
+
if (!isApiKey(key)) throw new Error(`createTestKeyVerifier: ${key} does not start with pk_`);
|
|
44
|
+
}
|
|
45
|
+
return createKeyVerifier({
|
|
46
|
+
async check(key) {
|
|
47
|
+
const given = Object.hasOwn(keys, key) ? keys[key] : void 0;
|
|
48
|
+
if (!given) return void 0;
|
|
49
|
+
const kind = given.kind ?? "user";
|
|
50
|
+
const keyId = given.key_id ?? `key-${key.slice(3)}`;
|
|
51
|
+
return {
|
|
52
|
+
subject: kind === "tenant" ? `key:${keyId}` : "user-test",
|
|
53
|
+
key_id: keyId,
|
|
54
|
+
tenant_id: TEST_TENANT_ID,
|
|
55
|
+
tenant_slug: "org-test",
|
|
56
|
+
username: kind === "tenant" ? keyId : "user-test",
|
|
57
|
+
roles: [],
|
|
58
|
+
permissions: [],
|
|
59
|
+
...given,
|
|
60
|
+
kind,
|
|
61
|
+
cache_seconds: 0
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
var MCP_PROTOCOL_VERSION = "2026-07-28";
|
|
67
|
+
function mcpRequest(url, method, params = {}, init = {}) {
|
|
68
|
+
const named = params.name ?? params.uri;
|
|
69
|
+
return new Request(url, {
|
|
70
|
+
method: "POST",
|
|
71
|
+
headers: {
|
|
72
|
+
"Content-Type": "application/json",
|
|
73
|
+
Accept: "application/json, text/event-stream",
|
|
74
|
+
"MCP-Protocol-Version": MCP_PROTOCOL_VERSION,
|
|
75
|
+
"Mcp-Method": method,
|
|
76
|
+
...typeof named === "string" ? { "Mcp-Name": named } : {},
|
|
77
|
+
...init.token ? { Authorization: `Bearer ${init.token}` } : {},
|
|
78
|
+
...init.headers
|
|
79
|
+
},
|
|
80
|
+
body: JSON.stringify({
|
|
81
|
+
jsonrpc: "2.0",
|
|
82
|
+
id: 1,
|
|
83
|
+
method,
|
|
84
|
+
params: {
|
|
85
|
+
...params,
|
|
86
|
+
_meta: {
|
|
87
|
+
"io.modelcontextprotocol/protocolVersion": MCP_PROTOCOL_VERSION,
|
|
88
|
+
"io.modelcontextprotocol/clientCapabilities": {},
|
|
89
|
+
"io.modelcontextprotocol/clientInfo": { name: "test", version: "1.0.0" }
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
})
|
|
93
|
+
});
|
|
94
|
+
}
|
|
38
95
|
export {
|
|
96
|
+
MCP_PROTOCOL_VERSION,
|
|
39
97
|
TEST_TENANT_ID,
|
|
40
|
-
createTestIssuer
|
|
98
|
+
createTestIssuer,
|
|
99
|
+
createTestKeyVerifier,
|
|
100
|
+
mcpRequest
|
|
41
101
|
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@zjazj/server",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.9",
|
|
4
4
|
"description": "Backend runtime for platform apps: auth, logging, tenant-safe database access and app assembly on Hono.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "UNLICENSED",
|
|
@@ -40,8 +40,10 @@
|
|
|
40
40
|
},
|
|
41
41
|
"dependencies": {
|
|
42
42
|
"@hono/node-server": "^1.19.18",
|
|
43
|
+
"@modelcontextprotocol/server": "^2.4.0",
|
|
43
44
|
"hono": "^4.13.17",
|
|
44
45
|
"jose": "^6.2.17",
|
|
46
|
+
"openid-client": "^6.9.1",
|
|
45
47
|
"pino": "^10.4.0"
|
|
46
48
|
},
|
|
47
49
|
"peerDependencies": {
|
|
@@ -63,7 +65,8 @@
|
|
|
63
65
|
"devDependencies": {
|
|
64
66
|
"@electric-sql/pglite": "^0.5.16",
|
|
65
67
|
"drizzle-orm": "^0.45.4",
|
|
66
|
-
"postgres": "^3.4.9"
|
|
68
|
+
"postgres": "^3.4.9",
|
|
69
|
+
"zod": "^4.6.7"
|
|
67
70
|
},
|
|
68
71
|
"publishConfig": {
|
|
69
72
|
"access": "public",
|
package/dist/auth-Ckmm4C6y.d.ts
DELETED
|
@@ -1,81 +0,0 @@
|
|
|
1
|
-
import { MiddlewareHandler, Context } from 'hono';
|
|
2
|
-
import { jwtVerify, JWTPayload } from 'jose';
|
|
3
|
-
|
|
4
|
-
/** The authenticated caller. */
|
|
5
|
-
interface AuthUser {
|
|
6
|
-
/** The identity provider's user id. An opaque string. */
|
|
7
|
-
id: string;
|
|
8
|
-
/** The tenant the token was issued for. A UUID. */
|
|
9
|
-
tenantId: string;
|
|
10
|
-
tenantSlug: string;
|
|
11
|
-
username: string;
|
|
12
|
-
roles: string[];
|
|
13
|
-
permissions: string[];
|
|
14
|
-
/** IANA time zone of the tenant, when the token carries one. */
|
|
15
|
-
timeZone?: string;
|
|
16
|
-
/**
|
|
17
|
-
* Set when a platform operator works in this tenant as platform support. `until` is when
|
|
18
|
-
* the session ends, in seconds since 1970. The subject is the operator.
|
|
19
|
-
*/
|
|
20
|
-
support?: SupportSession;
|
|
21
|
-
/** True only for the local dev identity. */
|
|
22
|
-
isDev?: boolean;
|
|
23
|
-
}
|
|
24
|
-
/** A platform operator's time in a customer's tenant, as the token states it. */
|
|
25
|
-
interface SupportSession {
|
|
26
|
-
until: number;
|
|
27
|
-
/** `support` today. */
|
|
28
|
-
mode: string;
|
|
29
|
-
}
|
|
30
|
-
/**
|
|
31
|
-
* The support session a token states, from `support_until` and `support_mode`. Both or
|
|
32
|
-
* nothing: half of it is not a session. Mirrored in `@zjazj/web`.
|
|
33
|
-
*/
|
|
34
|
-
declare function supportFromClaims(claims: Record<string, unknown>): SupportSession | undefined;
|
|
35
|
-
/** Organization tokens carry this audience prefix followed by the organization id. */
|
|
36
|
-
declare const ORGANIZATION_AUDIENCE_PREFIX = "urn:logto:organization:";
|
|
37
|
-
type VerifyKey = Parameters<typeof jwtVerify>[1];
|
|
38
|
-
interface VerifierOptions {
|
|
39
|
-
/** The token issuer, for example `https://auth.example.com/oidc`. */
|
|
40
|
-
issuer: string;
|
|
41
|
-
/** A fixed audience. Leave unset to accept organization tokens. */
|
|
42
|
-
audience?: string;
|
|
43
|
-
/** Defaults to `<issuer>/jwks`. */
|
|
44
|
-
jwksUri?: string;
|
|
45
|
-
/** A key or key resolver, used instead of fetching the JWKS. Meant for tests. */
|
|
46
|
-
key?: VerifyKey;
|
|
47
|
-
algorithms?: string[];
|
|
48
|
-
}
|
|
49
|
-
interface Verifier {
|
|
50
|
-
verify(token: string): Promise<AuthUser>;
|
|
51
|
-
}
|
|
52
|
-
/** Project verified token claims into an `AuthUser`. */
|
|
53
|
-
declare function userFromClaims(claims: JWTPayload): AuthUser;
|
|
54
|
-
/** Build a verifier for tokens issued by the platform's identity provider. */
|
|
55
|
-
declare function createVerifier(options: VerifierOptions): Verifier;
|
|
56
|
-
type Env = Record<string, string | undefined>;
|
|
57
|
-
/** Build the verifier from `LOGTO_ISSUER`, `LOGTO_AUDIENCE` and `LOGTO_JWKS_URI`. */
|
|
58
|
-
declare function verifierFromEnv(env?: Env): Verifier | undefined;
|
|
59
|
-
declare function bearerToken(header: string | undefined): string | undefined;
|
|
60
|
-
interface AuthenticateOptions {
|
|
61
|
-
verifier?: Verifier;
|
|
62
|
-
env?: Env;
|
|
63
|
-
}
|
|
64
|
-
/**
|
|
65
|
-
* Require an authenticated caller. On success the user is available through `getUser(c)`.
|
|
66
|
-
* With the dev identity enabled no token is verified and every request is the dev user.
|
|
67
|
-
*/
|
|
68
|
-
declare function authenticate(options?: AuthenticateOptions): MiddlewareHandler;
|
|
69
|
-
/** The authenticated user of this request. Throws 401 when the route is not authenticated. */
|
|
70
|
-
declare function getUser(c: Context): AuthUser;
|
|
71
|
-
/** Require every listed permission. Wildcards in the granted set count. */
|
|
72
|
-
declare function requirePermission(...codes: string[]): MiddlewareHandler;
|
|
73
|
-
/** Require at least one of the listed roles. */
|
|
74
|
-
declare function requireRole(...roles: string[]): MiddlewareHandler;
|
|
75
|
-
declare module 'hono' {
|
|
76
|
-
interface ContextVariableMap {
|
|
77
|
-
user: AuthUser;
|
|
78
|
-
}
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
export { type AuthUser as A, ORGANIZATION_AUDIENCE_PREFIX as O, type SupportSession as S, type Verifier as V, type AuthenticateOptions as a, type VerifierOptions as b, authenticate as c, bearerToken as d, createVerifier as e, requireRole as f, getUser as g, requirePermission as r, supportFromClaims as s, userFromClaims as u, verifierFromEnv as v };
|
package/dist/chunk-UWDDQH25.js
DELETED
|
@@ -1,146 +0,0 @@
|
|
|
1
|
-
import {
|
|
2
|
-
getRequestId
|
|
3
|
-
} from "./chunk-ERGI2X5S.js";
|
|
4
|
-
|
|
5
|
-
// src/errors.ts
|
|
6
|
-
import { HTTPException } from "hono/http-exception";
|
|
7
|
-
var AppError = class extends Error {
|
|
8
|
-
code;
|
|
9
|
-
status;
|
|
10
|
-
field;
|
|
11
|
-
constructor(message, options = {}) {
|
|
12
|
-
super(message, options.cause === void 0 ? void 0 : { cause: options.cause });
|
|
13
|
-
this.name = new.target.name;
|
|
14
|
-
this.code = options.code ?? "app_error";
|
|
15
|
-
this.status = options.status ?? 400;
|
|
16
|
-
this.field = options.field;
|
|
17
|
-
}
|
|
18
|
-
};
|
|
19
|
-
var UnauthorizedError = class extends AppError {
|
|
20
|
-
constructor(message = "Authentication required", options = {}) {
|
|
21
|
-
super(message, { code: "unauthorized", status: 401, ...options });
|
|
22
|
-
}
|
|
23
|
-
};
|
|
24
|
-
var ForbiddenError = class extends AppError {
|
|
25
|
-
constructor(message = "Forbidden", options = {}) {
|
|
26
|
-
super(message, { code: "forbidden", status: 403, ...options });
|
|
27
|
-
}
|
|
28
|
-
};
|
|
29
|
-
var NotFoundError = class extends AppError {
|
|
30
|
-
constructor(message = "Not found", options = {}) {
|
|
31
|
-
super(message, { code: "not_found", status: 404, ...options });
|
|
32
|
-
}
|
|
33
|
-
};
|
|
34
|
-
var ConflictError = class extends AppError {
|
|
35
|
-
constructor(message = "Conflict", options = {}) {
|
|
36
|
-
super(message, { code: "conflict", status: 409, ...options });
|
|
37
|
-
}
|
|
38
|
-
};
|
|
39
|
-
var ValidationError = class extends AppError {
|
|
40
|
-
constructor(message, field, options = {}) {
|
|
41
|
-
super(message, { code: "validation_error", status: 422, field, ...options });
|
|
42
|
-
}
|
|
43
|
-
};
|
|
44
|
-
function withTrace(body) {
|
|
45
|
-
const traceId = getRequestId();
|
|
46
|
-
return traceId ? { ...body, trace_id: traceId } : body;
|
|
47
|
-
}
|
|
48
|
-
function toErrorResponse(error) {
|
|
49
|
-
if (error instanceof AppError) {
|
|
50
|
-
const body = { code: error.code, message: error.message };
|
|
51
|
-
if (error.field) body.field = error.field;
|
|
52
|
-
return { status: error.status, body: withTrace(body) };
|
|
53
|
-
}
|
|
54
|
-
if (error instanceof HTTPException) {
|
|
55
|
-
const code = error.status === 404 ? "not_found" : error.status >= 500 ? "internal_error" : "http_error";
|
|
56
|
-
return {
|
|
57
|
-
status: error.status,
|
|
58
|
-
body: withTrace({ code, message: error.message || "Request failed" })
|
|
59
|
-
};
|
|
60
|
-
}
|
|
61
|
-
return {
|
|
62
|
-
status: 500,
|
|
63
|
-
body: withTrace({ code: "internal_error", message: "Internal server error" })
|
|
64
|
-
};
|
|
65
|
-
}
|
|
66
|
-
function respond(c, status, body) {
|
|
67
|
-
if (status === 401) c.header("WWW-Authenticate", "Bearer");
|
|
68
|
-
return c.json(body, status);
|
|
69
|
-
}
|
|
70
|
-
function errorHandler(onUnexpected) {
|
|
71
|
-
return (error, c) => {
|
|
72
|
-
const { status, body } = toErrorResponse(error);
|
|
73
|
-
if (status >= 500) onUnexpected?.(error, c);
|
|
74
|
-
return respond(c, status, body);
|
|
75
|
-
};
|
|
76
|
-
}
|
|
77
|
-
function notFoundHandler() {
|
|
78
|
-
return (c) => respond(c, 404, withTrace({ code: "not_found", message: "Not found" }));
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
// src/ids.ts
|
|
82
|
-
import { randomBytes, randomInt } from "crypto";
|
|
83
|
-
var APP_NAME_PATTERN = /^[a-z][a-z0-9-]{1,30}$/;
|
|
84
|
-
var APP_ID_PATTERN = /^app[a-z0-9]{6}$/;
|
|
85
|
-
var UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
86
|
-
var ID_ALPHABET = "abcdefghijklmnopqrstuvwxyz0123456789";
|
|
87
|
-
function isUuid(value) {
|
|
88
|
-
return typeof value === "string" && UUID_PATTERN.test(value);
|
|
89
|
-
}
|
|
90
|
-
function isValidAppName(value) {
|
|
91
|
-
return typeof value === "string" && APP_NAME_PATTERN.test(value);
|
|
92
|
-
}
|
|
93
|
-
function isValidAppId(value) {
|
|
94
|
-
return typeof value === "string" && APP_ID_PATTERN.test(value);
|
|
95
|
-
}
|
|
96
|
-
function appBasePath(name) {
|
|
97
|
-
return `/apps/${name}/`;
|
|
98
|
-
}
|
|
99
|
-
function assertValidAppId(value) {
|
|
100
|
-
if (!isValidAppId(value)) {
|
|
101
|
-
throw new Error(
|
|
102
|
-
`Invalid app id ${JSON.stringify(value)}. Expected "app" followed by six characters from [a-z0-9].`
|
|
103
|
-
);
|
|
104
|
-
}
|
|
105
|
-
}
|
|
106
|
-
function generateAppId() {
|
|
107
|
-
let id = "app";
|
|
108
|
-
for (let i = 0; i < 6; i += 1) id += ID_ALPHABET[randomInt(ID_ALPHABET.length)];
|
|
109
|
-
return id;
|
|
110
|
-
}
|
|
111
|
-
function uuidv7(now = Date.now()) {
|
|
112
|
-
const bytes = randomBytes(16);
|
|
113
|
-
const time = BigInt(now);
|
|
114
|
-
bytes[0] = Number(time >> 40n & 0xffn);
|
|
115
|
-
bytes[1] = Number(time >> 32n & 0xffn);
|
|
116
|
-
bytes[2] = Number(time >> 24n & 0xffn);
|
|
117
|
-
bytes[3] = Number(time >> 16n & 0xffn);
|
|
118
|
-
bytes[4] = Number(time >> 8n & 0xffn);
|
|
119
|
-
bytes[5] = Number(time & 0xffn);
|
|
120
|
-
bytes[6] = (bytes[6] ?? 0) & 15 | 112;
|
|
121
|
-
bytes[8] = (bytes[8] ?? 0) & 63 | 128;
|
|
122
|
-
const hex = bytes.toString("hex");
|
|
123
|
-
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
|
124
|
-
}
|
|
125
|
-
|
|
126
|
-
export {
|
|
127
|
-
AppError,
|
|
128
|
-
UnauthorizedError,
|
|
129
|
-
ForbiddenError,
|
|
130
|
-
NotFoundError,
|
|
131
|
-
ConflictError,
|
|
132
|
-
ValidationError,
|
|
133
|
-
toErrorResponse,
|
|
134
|
-
errorHandler,
|
|
135
|
-
notFoundHandler,
|
|
136
|
-
APP_NAME_PATTERN,
|
|
137
|
-
APP_ID_PATTERN,
|
|
138
|
-
UUID_PATTERN,
|
|
139
|
-
isUuid,
|
|
140
|
-
isValidAppName,
|
|
141
|
-
isValidAppId,
|
|
142
|
-
appBasePath,
|
|
143
|
-
assertValidAppId,
|
|
144
|
-
generateAppId,
|
|
145
|
-
uuidv7
|
|
146
|
-
};
|