@agentage/extension 0.8.0 → 0.10.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/dist/agcid/agcid.d.ts +1 -3
- package/dist/agcid/agcid.js +2 -3
- package/dist/agcid/header.d.ts +3 -0
- package/dist/agcid/header.js +3 -0
- package/dist/api/openapi-doc.d.ts +1 -0
- package/dist/api/openapi-doc.js +15 -10
- package/dist/api/routes.d.ts +15 -6
- package/dist/api/routes.js +2 -5
- package/dist/auth/part-auth.d.ts +3 -0
- package/dist/auth/part-auth.js +12 -1
- package/dist/auth/route-access.d.ts +1 -0
- package/dist/auth/route-access.js +1 -1
- package/dist/auth/token-check.d.ts +5 -2
- package/dist/auth/token-check.js +10 -3
- package/dist/auth/verify-token.js +2 -2
- package/dist/command/cli-context.js +4 -1
- package/dist/command/command.types.d.ts +2 -0
- package/dist/command/command.types.js +1 -0
- package/dist/context/context.d.ts +10 -0
- package/dist/context/context.js +14 -1
- package/dist/context/recording-log.js +3 -3
- package/dist/context/test-command-context.d.ts +2 -0
- package/dist/context/test-command-context.js +13 -4
- package/dist/context/test-context.d.ts +4 -1
- package/dist/context/test-context.js +6 -1
- package/dist/contracts/index.d.ts +6 -0
- package/dist/contracts/index.js +6 -0
- package/dist/envelope/envelope.d.ts +8 -5
- package/dist/envelope/envelope.js +15 -3
- package/dist/envelope/envelope.schema.d.ts +3 -5
- package/dist/envelope/envelope.schema.js +8 -4
- package/dist/index.d.ts +9 -12
- package/dist/index.js +8 -10
- package/dist/log/log.d.ts +3 -0
- package/dist/log/log.js +7 -3
- package/dist/log/span.d.ts +9 -0
- package/dist/log/span.js +19 -0
- package/dist/mcp/tools.js +5 -4
- package/dist/pages/inline-hashes.d.ts +3 -0
- package/dist/pages/inline-hashes.js +27 -0
- package/dist/pages/pages-app.js +22 -11
- package/dist/pages/pages.d.ts +5 -1
- package/dist/pages/site-from-dir.d.ts +7 -0
- package/dist/pages/site-from-dir.js +31 -0
- package/dist/pages/types.d.ts +3 -0
- package/dist/pages/types.js +40 -0
- package/dist/runtime/build-info.d.ts +1 -0
- package/dist/runtime/build-info.js +2 -1
- package/dist/runtime/part-runners.js +9 -2
- package/dist/runtime/run-part.js +2 -1
- package/dist/server/api-routes.js +16 -3
- package/dist/server/app.d.ts +4 -0
- package/dist/server/app.js +13 -2
- package/dist/testing/test-server.js +1 -1
- package/dist/tool/build-info.js +4 -4
- package/dist/tool/index.d.ts +4 -1
- package/dist/tool/index.js +4 -1
- package/dist/worker/run-log.js +7 -3
- package/package.json +5 -1
- package/schemas/error-envelope.schema.json +27 -27
|
@@ -15,10 +15,18 @@ const retryAfterOf = (code, given) => {
|
|
|
15
15
|
return given;
|
|
16
16
|
return RETRY_AFTER_CODES.includes(code) ? DEFAULT_RETRY_AFTER_SECONDS : undefined;
|
|
17
17
|
};
|
|
18
|
+
const UPPER_SNAKE = /^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$/;
|
|
19
|
+
const wireCode = (code, override) => {
|
|
20
|
+
if (override === undefined)
|
|
21
|
+
return code;
|
|
22
|
+
if (ERROR_STATUS[code] >= 500 || !UPPER_SNAKE.test(override))
|
|
23
|
+
throw new Error(`fail code ${override}: UPPER_SNAKE on a 4xx only`);
|
|
24
|
+
return override;
|
|
25
|
+
};
|
|
18
26
|
// Returned, not thrown, so a route reads `throw fail(...)`; the kit turns it into the envelope.
|
|
19
27
|
export const fail = (code, message, options = {}) => Object.assign(new Error(message), {
|
|
20
28
|
[FAILURE]: true,
|
|
21
|
-
code,
|
|
29
|
+
code: wireCode(code, options.code),
|
|
22
30
|
status: ERROR_STATUS[code],
|
|
23
31
|
details: options.details,
|
|
24
32
|
retryAfter: retryAfterOf(code, options.retryAfter),
|
|
@@ -27,7 +35,11 @@ export const fail = (code, message, options = {}) => Object.assign(new Error(mes
|
|
|
27
35
|
export const isFailure = (err) => err instanceof Error && err[FAILURE] === true;
|
|
28
36
|
export const errorEnvelope = (failure, agcid) => {
|
|
29
37
|
const error = { code: failure.code, message: failure.message, agcid };
|
|
30
|
-
|
|
31
|
-
|
|
38
|
+
const details = failure.status >= 500 ? undefined : failure.details;
|
|
39
|
+
const filled = Array.isArray(details)
|
|
40
|
+
? details.length > 0
|
|
41
|
+
: details && Object.keys(details).length > 0;
|
|
42
|
+
if (details && filled)
|
|
43
|
+
error.details = details;
|
|
32
44
|
return { success: false, error };
|
|
33
45
|
};
|
|
@@ -2,15 +2,13 @@ import { z } from 'zod';
|
|
|
2
2
|
export declare const ErrorEnvelopeSchema: z.ZodObject<{
|
|
3
3
|
success: z.ZodLiteral<false>;
|
|
4
4
|
error: z.ZodObject<{
|
|
5
|
-
code: z.
|
|
6
|
-
[x: string]: string;
|
|
7
|
-
}>;
|
|
5
|
+
code: z.ZodString;
|
|
8
6
|
message: z.ZodString;
|
|
9
7
|
agcid: z.ZodString;
|
|
10
|
-
details: z.ZodOptional<z.ZodArray<z.ZodObject<{
|
|
8
|
+
details: z.ZodOptional<z.ZodUnion<readonly [z.ZodArray<z.ZodObject<{
|
|
11
9
|
field: z.ZodString;
|
|
12
10
|
message: z.ZodString;
|
|
13
|
-
}, z.core.$strict
|
|
11
|
+
}, z.core.$strict>>, z.ZodRecord<z.ZodString, z.ZodUnknown>]>>;
|
|
14
12
|
}, z.core.$strict>;
|
|
15
13
|
}, z.core.$strict>;
|
|
16
14
|
export declare const OkEnvelopeSchema: z.ZodObject<{
|
|
@@ -1,15 +1,19 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
|
-
import { AGCID_PATTERN } from '../agcid/
|
|
3
|
-
import { ERROR_CODES } from './codes.js';
|
|
2
|
+
import { AGCID_PATTERN } from '../agcid/header.js';
|
|
4
3
|
const AgcidSchema = z.string().regex(AGCID_PATTERN);
|
|
5
|
-
const ErrorCodeSchema = z.
|
|
4
|
+
const ErrorCodeSchema = z.string().regex(/^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$/);
|
|
6
5
|
export const ErrorEnvelopeSchema = z.strictObject({
|
|
7
6
|
success: z.literal(false),
|
|
8
7
|
error: z.strictObject({
|
|
9
8
|
code: ErrorCodeSchema,
|
|
10
9
|
message: z.string().min(1),
|
|
11
10
|
agcid: AgcidSchema,
|
|
12
|
-
details: z
|
|
11
|
+
details: z
|
|
12
|
+
.union([
|
|
13
|
+
z.array(z.strictObject({ field: z.string(), message: z.string() })),
|
|
14
|
+
z.record(z.string(), z.unknown()),
|
|
15
|
+
])
|
|
16
|
+
.optional(),
|
|
13
17
|
}),
|
|
14
18
|
});
|
|
15
19
|
export const OkEnvelopeSchema = z.strictObject({
|
package/dist/index.d.ts
CHANGED
|
@@ -4,24 +4,21 @@ export { type Access, type Caller } from './auth/token-check.js';
|
|
|
4
4
|
export { type ArgValue } from './command/args.js';
|
|
5
5
|
export { type CliClient, type CliContext, type CliCreate, type CommandExtension, type CommandHandler, } from './command/command.types.js';
|
|
6
6
|
export { type Out } from './command/out.js';
|
|
7
|
-
export { type ExtensionInfo, type PartContext, type ServerPartKind, type SettingValue, } from './context/context.js';
|
|
7
|
+
export { type ExtensionInfo, type PartContext, type PlatformInfo, type ServerPartKind, type SettingValue, } from './context/context.js';
|
|
8
8
|
export { type Secrets } from './context/secrets.js';
|
|
9
9
|
export { createTestContext, type ClientCall, type LogEntry, type ScheduledJob, type TestCommandContext, type TestCommandOptions, type TestContext, type TestContextOptions, } from './context/test-context.js';
|
|
10
|
-
export {
|
|
11
|
-
export {
|
|
12
|
-
export {
|
|
13
|
-
export {
|
|
10
|
+
export { type DiscoveryDocument, type ExtensionRecord } from './discovery/discovery.schema.js';
|
|
11
|
+
export { ERROR_STATUS, type ErrorCode } from './envelope/codes.js';
|
|
12
|
+
export { fail, ok, reply, type ErrorDetail, type ErrorEnvelope, type Failure, type FailOptions, type OkEnvelope, type Reply, type ReplyOptions, } from './envelope/envelope.js';
|
|
13
|
+
export { DiscoveryDocumentSchema } from './discovery/discovery.schema.js';
|
|
14
14
|
export { ErrorEnvelopeSchema, OkEnvelopeSchema } from './envelope/envelope.schema.js';
|
|
15
15
|
export { parse, type ParseSchema } from './envelope/parse.js';
|
|
16
|
-
export {
|
|
16
|
+
export { type HealthBody, type HealthStatus } from './health/health.schema.js';
|
|
17
17
|
export { type Log, type LogFields } from './log/log.js';
|
|
18
|
-
export {
|
|
19
|
-
export { imageParts } from './manifest/parts.js';
|
|
20
|
-
export { SERVED_KINDS, STORE_KINDS, type StoreKind } from './manifest/primitives.schema.js';
|
|
21
|
-
export { readManifest, validateManifest } from './manifest/read-manifest.js';
|
|
22
|
-
export { canonical, mcpSnapshot, PROTOCOL_VERSIONS, type McpSnapshot, type ProtocolVersion, } from './mcp/snapshot.js';
|
|
18
|
+
export { type Span, type SpanRecord } from './log/span.js';
|
|
23
19
|
export { type McpContext, type ToolHandler, type ToolRegistrar, type ToolSpec, } from './mcp/tools.js';
|
|
24
|
-
export { versionPage, type PagesContext, type PagesSite } from './pages/pages.js';
|
|
20
|
+
export { versionPage, type PagesContext, type PagesEntry, type PagesSite } from './pages/pages.js';
|
|
21
|
+
export { siteFromDir, type SiteFromDirOptions } from './pages/site-from-dir.js';
|
|
25
22
|
export { type ApiCreate, type ApiHandler, type ApiPart } from './server/part.types.js';
|
|
26
23
|
export { type QueryResult, type Row, type Store } from './store/store.types.js';
|
|
27
24
|
export { startTestMcp, startTestServer, type TestMcp, type TestMcpOptions, type TestServer, type TestServerOptions, } from './testing/test-server.js';
|
package/dist/index.js
CHANGED
|
@@ -7,21 +7,19 @@ export {} from './command/out.js';
|
|
|
7
7
|
export {} from './context/context.js';
|
|
8
8
|
export {} from './context/secrets.js';
|
|
9
9
|
export { createTestContext, } from './context/test-context.js';
|
|
10
|
-
export {
|
|
11
|
-
export {
|
|
12
|
-
export {
|
|
13
|
-
|
|
10
|
+
export {} from './discovery/discovery.schema.js';
|
|
11
|
+
export { ERROR_STATUS } from './envelope/codes.js';
|
|
12
|
+
export { fail, ok, reply, } from './envelope/envelope.js';
|
|
13
|
+
// Also in /contracts: main drops them once probe master's e2e reads them from there.
|
|
14
|
+
export { DiscoveryDocumentSchema } from './discovery/discovery.schema.js';
|
|
14
15
|
export { ErrorEnvelopeSchema, OkEnvelopeSchema } from './envelope/envelope.schema.js';
|
|
15
16
|
export { parse } from './envelope/parse.js';
|
|
16
|
-
export {
|
|
17
|
+
export {} from './health/health.schema.js';
|
|
17
18
|
export {} from './log/log.js';
|
|
18
|
-
export {
|
|
19
|
-
export { imageParts } from './manifest/parts.js';
|
|
20
|
-
export { SERVED_KINDS, STORE_KINDS } from './manifest/primitives.schema.js';
|
|
21
|
-
export { readManifest, validateManifest } from './manifest/read-manifest.js';
|
|
22
|
-
export { canonical, mcpSnapshot, PROTOCOL_VERSIONS, } from './mcp/snapshot.js';
|
|
19
|
+
export {} from './log/span.js';
|
|
23
20
|
export {} from './mcp/tools.js';
|
|
24
21
|
export { versionPage } from './pages/pages.js';
|
|
22
|
+
export { siteFromDir } from './pages/site-from-dir.js';
|
|
25
23
|
export {} from './server/part.types.js';
|
|
26
24
|
export {} from './store/store.types.js';
|
|
27
25
|
export { startTestMcp, startTestServer, } from './testing/test-server.js';
|
package/dist/log/log.d.ts
CHANGED
|
@@ -13,5 +13,8 @@ export interface LogTags {
|
|
|
13
13
|
}
|
|
14
14
|
export type LogWrite = (line: string) => void;
|
|
15
15
|
export declare const messageOf: (error: unknown) => string;
|
|
16
|
+
export declare const errorFields: (error: unknown) => LogFields;
|
|
17
|
+
export type LineAt = (level: LogLevel, message: string, fields: LogFields) => void;
|
|
18
|
+
export declare const withLineAt: (log: Log, at: LineAt) => Log;
|
|
16
19
|
export declare const createLog: (tags: LogTags, write?: LogWrite) => Log;
|
|
17
20
|
export declare const logAt: (log: Log, level: LogLevel, message: string, fields: LogFields) => void;
|
package/dist/log/log.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { currentAgcid } from '../agcid/current.js';
|
|
2
2
|
export const messageOf = (error) => error instanceof Error ? error.message : String(error);
|
|
3
|
-
const errorFields = (error) => {
|
|
3
|
+
export const errorFields = (error) => {
|
|
4
4
|
if (!(error instanceof Error))
|
|
5
5
|
return { err: { message: String(error) } };
|
|
6
6
|
return { err: { type: error.name, message: error.message, stack: error.stack } };
|
|
@@ -16,6 +16,11 @@ const line = (level, message, tags, fields) => {
|
|
|
16
16
|
};
|
|
17
17
|
const stderrWrite = (text) => void process.stderr.write(text);
|
|
18
18
|
const raw = new WeakMap();
|
|
19
|
+
// Registers how a Log writes a line as given, so logAt keeps every field on it.
|
|
20
|
+
export const withLineAt = (log, at) => {
|
|
21
|
+
raw.set(log, at);
|
|
22
|
+
return log;
|
|
23
|
+
};
|
|
19
24
|
export const createLog = (tags, write = stderrWrite) => {
|
|
20
25
|
const at = (level, message, fields) => write(line(level, message, tags, fields));
|
|
21
26
|
const log = {
|
|
@@ -23,8 +28,7 @@ export const createLog = (tags, write = stderrWrite) => {
|
|
|
23
28
|
warn: (message, fields = {}) => at('warn', message, fields),
|
|
24
29
|
error: (error, fields = {}) => at('error', messageOf(error), { ...fields, ...errorFields(error) }),
|
|
25
30
|
};
|
|
26
|
-
|
|
27
|
-
return log;
|
|
31
|
+
return withLineAt(log, at);
|
|
28
32
|
};
|
|
29
33
|
// A line at any level with no err field (an error-level line that is not an error event).
|
|
30
34
|
export const logAt = (log, level, message, fields) => {
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { type Log } from './log.js';
|
|
2
|
+
export interface SpanRecord {
|
|
3
|
+
name: string;
|
|
4
|
+
ms: number;
|
|
5
|
+
ok: boolean;
|
|
6
|
+
err?: unknown;
|
|
7
|
+
}
|
|
8
|
+
export type Span = <T>(name: string, fn: () => T | Promise<T>) => Promise<T>;
|
|
9
|
+
export declare const createSpan: (log: Log, spans?: SpanRecord[]) => Span;
|
package/dist/log/span.js
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { errorFields, logAt } from './log.js';
|
|
2
|
+
// One line per span; a nested span is its own line, the agcid on both links them.
|
|
3
|
+
export const createSpan = (log, spans) => async (name, fn) => {
|
|
4
|
+
const start = performance.now();
|
|
5
|
+
const end = (ok, err) => {
|
|
6
|
+
const span = { name, ms: Math.round(performance.now() - start), ok };
|
|
7
|
+
spans?.push(ok ? span : { ...span, err });
|
|
8
|
+
logAt(log, ok ? 'info' : 'error', 'span', ok ? span : { ...span, ...errorFields(err) });
|
|
9
|
+
};
|
|
10
|
+
try {
|
|
11
|
+
const value = await fn();
|
|
12
|
+
end(true);
|
|
13
|
+
return value;
|
|
14
|
+
}
|
|
15
|
+
catch (err) {
|
|
16
|
+
end(false, err);
|
|
17
|
+
throw err;
|
|
18
|
+
}
|
|
19
|
+
};
|
package/dist/mcp/tools.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import {} from 'zod';
|
|
2
|
-
import {} from '../auth/token-check.js';
|
|
2
|
+
import { ACCESS, badScope } from '../auth/token-check.js';
|
|
3
3
|
import {} from '../context/context.js';
|
|
4
4
|
const TOOL_NAME = /^[a-z][a-z0-9_-]*$/;
|
|
5
|
-
const
|
|
5
|
+
const TOOL_ACCESS = ACCESS.filter((access) => access !== 'optional');
|
|
6
6
|
export const createToolRegistry = () => {
|
|
7
7
|
const tools = [];
|
|
8
8
|
const tool = (name, spec, handler) => {
|
|
@@ -12,8 +12,9 @@ export const createToolRegistry = () => {
|
|
|
12
12
|
throw new Error(`tool ${name} is registered twice`);
|
|
13
13
|
if (!spec.description)
|
|
14
14
|
throw new Error(`tool ${name} needs a description: it routes the model`);
|
|
15
|
-
|
|
16
|
-
|
|
15
|
+
const bad = badScope(spec.scope, TOOL_ACCESS);
|
|
16
|
+
if (bad)
|
|
17
|
+
throw new Error(`tool ${name} ${bad}`);
|
|
17
18
|
tools.push({ name, spec, handler: handler });
|
|
18
19
|
};
|
|
19
20
|
return { tool, tools };
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import {} from './pages.js';
|
|
3
|
+
import { typeOf } from './types.js';
|
|
4
|
+
const SCRIPT = /<script\b([^>]*)>([\s\S]*?)<\/script\s*>/gi;
|
|
5
|
+
const EXECUTES = /\btype\s*=\s*["']?(module|text\/javascript|application\/javascript)\b|^((?!\btype\s*=).)*$/is;
|
|
6
|
+
const sha256 = (text) => `'sha256-${createHash('sha256').update(text, 'utf8').digest('base64')}'`;
|
|
7
|
+
// CSP hashes of the inline scripts an HTML page runs, so script-src never needs 'unsafe-inline'.
|
|
8
|
+
export const inlineScriptHashes = (html) => {
|
|
9
|
+
const hashes = new Set();
|
|
10
|
+
for (const [, attrs = '', body = ''] of html.matchAll(SCRIPT))
|
|
11
|
+
if (body.trim() !== '' && !/\bsrc\s*=/i.test(attrs) && EXECUTES.test(attrs))
|
|
12
|
+
hashes.add(sha256(body));
|
|
13
|
+
return [...hashes];
|
|
14
|
+
};
|
|
15
|
+
// Path -> hashes, for the HTML entries that have inline scripts.
|
|
16
|
+
export const siteScriptHashes = (site) => {
|
|
17
|
+
const found = new Map();
|
|
18
|
+
for (const [path, entry] of Object.entries(site)) {
|
|
19
|
+
const { type = typeOf(path), body = entry } = typeof entry === 'object' && 'type' in entry ? entry : {};
|
|
20
|
+
if (!type.startsWith('text/html') || typeof body !== 'string')
|
|
21
|
+
continue;
|
|
22
|
+
const hashes = inlineScriptHashes(body);
|
|
23
|
+
if (hashes.length > 0)
|
|
24
|
+
found.set(path, hashes);
|
|
25
|
+
}
|
|
26
|
+
return found;
|
|
27
|
+
};
|
package/dist/pages/pages-app.js
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import {} from 'node:http';
|
|
2
2
|
import {} from 'express';
|
|
3
3
|
import { z } from 'zod';
|
|
4
|
+
import { isAudience } from '../auth/part-auth.js';
|
|
4
5
|
import {} from '../runtime/build-info.js';
|
|
5
6
|
import { createPartApp } from '../server/app.js';
|
|
7
|
+
import { siteScriptHashes } from './inline-hashes.js';
|
|
6
8
|
import {} from './pages.js';
|
|
7
|
-
|
|
8
|
-
const AUDIENCE = /^(\*\.[a-z0-9-]+(\.[a-z0-9-]+)+|[a-z0-9-]+(\.[a-z0-9-]+)*)(:\d+)?$/;
|
|
9
|
+
import { typeOf } from './types.js';
|
|
9
10
|
const WEB = ['http:', 'https:'];
|
|
10
11
|
const webUrl = (url) => {
|
|
11
12
|
const parsed = url && URL.canParse(url) ? new URL(url) : undefined;
|
|
@@ -16,17 +17,20 @@ export const platformSources = (env) => {
|
|
|
16
17
|
const issuer = webUrl(env['AGENTAGE_ISSUER'])?.origin;
|
|
17
18
|
const scheme = webUrl(env['AGENTAGE_ORIGIN'])?.protocol ?? 'https:';
|
|
18
19
|
const audience = env['AGENTAGE_AUDIENCE'] ?? '';
|
|
19
|
-
return [issuer,
|
|
20
|
+
return [issuer, isAudience(audience) ? `${scheme}//${audience}` : undefined].filter((source) => Boolean(source));
|
|
20
21
|
};
|
|
21
|
-
const
|
|
22
|
-
const
|
|
22
|
+
const BODY = z.union([z.string(), z.instanceof(Uint8Array)]);
|
|
23
|
+
const ENTRY = z.union([BODY, z.object({ type: z.string().min(1), body: BODY })]);
|
|
24
|
+
const SiteSchema = z.record(z.string().regex(/^\/[A-Za-z0-9._~$/-]*$/), ENTRY);
|
|
23
25
|
export const NOT_FOUND_PAGE = '<!doctype html>\n<html lang="en"><head><meta charset="utf-8"><title>Not found</title></head><body><p>Not found</p></body></html>\n';
|
|
24
26
|
const serve = (site) => (req, res, next) => {
|
|
25
|
-
const
|
|
26
|
-
if (
|
|
27
|
+
const entry = site[req.path];
|
|
28
|
+
if (entry === undefined)
|
|
27
29
|
return next();
|
|
28
|
-
|
|
29
|
-
res.
|
|
30
|
+
const { type, body } = typeof entry === 'object' && 'type' in entry ? entry : { body: entry };
|
|
31
|
+
res.type(type ?? typeOf(req.path)).setHeader('Cache-Control', 'no-cache');
|
|
32
|
+
// express sends a Buffer as bytes but a plain Uint8Array as JSON.
|
|
33
|
+
res.send(typeof body === 'string' ? body : Buffer.from(body.buffer, body.byteOffset, body.length));
|
|
30
34
|
};
|
|
31
35
|
const missing = (_req, res) => {
|
|
32
36
|
res.status(404).type('html').send(NOT_FOUND_PAGE);
|
|
@@ -34,13 +38,20 @@ const missing = (_req, res) => {
|
|
|
34
38
|
// Everything the gateway does not reserve comes here: a site map entry (typed by its extension), or an HTML 404.
|
|
35
39
|
export const createPagesApp = (options) => {
|
|
36
40
|
const site = SiteSchema.parse(options.site);
|
|
41
|
+
const hashes = siteScriptHashes(site);
|
|
42
|
+
const platform = options.platform ?? [];
|
|
43
|
+
const scripts = (req) => [
|
|
44
|
+
"'self'",
|
|
45
|
+
...platform,
|
|
46
|
+
...(hashes.get(new URL(req.url ?? '/', 'http://x').pathname) ?? []),
|
|
47
|
+
].join(' ');
|
|
37
48
|
return createPartApp({
|
|
38
49
|
...options,
|
|
39
50
|
part: 'pages',
|
|
40
51
|
helmet: {
|
|
41
52
|
contentSecurityPolicy: {
|
|
42
53
|
directives: {
|
|
43
|
-
scriptSrc: [
|
|
54
|
+
scriptSrc: [scripts],
|
|
44
55
|
connectSrc: ["'self'", ...(options.platform ?? [])],
|
|
45
56
|
upgradeInsecureRequests: null,
|
|
46
57
|
},
|
package/dist/pages/pages.d.ts
CHANGED
|
@@ -1,4 +1,8 @@
|
|
|
1
1
|
import { type PartContext } from '../context/context.js';
|
|
2
2
|
export type PagesContext = PartContext;
|
|
3
|
-
export type
|
|
3
|
+
export type PagesEntry = string | Uint8Array | {
|
|
4
|
+
type: string;
|
|
5
|
+
body: string | Uint8Array;
|
|
6
|
+
};
|
|
7
|
+
export type PagesSite = Readonly<Record<string, PagesEntry>>;
|
|
4
8
|
export declare const versionPage: (ctx: PagesContext) => string;
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { readdirSync, readFileSync } from 'node:fs';
|
|
2
|
+
import { join, relative, sep } from 'node:path';
|
|
3
|
+
import {} from './pages.js';
|
|
4
|
+
import { isText, typeOf } from './types.js';
|
|
5
|
+
const SITE_PLACEHOLDER = 'site-fqdn.sentinel.invalid';
|
|
6
|
+
// index.html is /, a/index.html and a.html are /a; every other file keeps its path.
|
|
7
|
+
const pathOf = (file) => `/${file.split(sep).join('/')}`.replace(/\/index\.html$|\.html$/, '') || '/';
|
|
8
|
+
const escaped = (token) => token.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
9
|
+
const entryOf = (bytes, type, own, rewrite, host) => {
|
|
10
|
+
const body = isText(type) ? bytes.toString('utf8').replace(rewrite, host) : bytes;
|
|
11
|
+
return own ? { type, body } : body;
|
|
12
|
+
};
|
|
13
|
+
// A static export (Next.js out/) as a pages site: text with the placeholder host rewritten, the rest as bytes.
|
|
14
|
+
export const siteFromDir = (dir, opts) => {
|
|
15
|
+
const host = new URL(opts.origin).host;
|
|
16
|
+
const rewrite = new RegExp(escaped(opts.placeholder ?? SITE_PLACEHOLDER), 'gi');
|
|
17
|
+
const files = readdirSync(dir, { recursive: true, withFileTypes: true }).filter((e) => e.isFile());
|
|
18
|
+
const site = {};
|
|
19
|
+
const from = {};
|
|
20
|
+
for (const file of files) {
|
|
21
|
+
const name = relative(dir, join(file.parentPath, file.name));
|
|
22
|
+
const path = pathOf(name);
|
|
23
|
+
if (path in from)
|
|
24
|
+
throw new Error(`siteFromDir: ${from[path]} and ${name} both map to ${path}`);
|
|
25
|
+
from[path] = name;
|
|
26
|
+
const own = opts.types?.[path];
|
|
27
|
+
const bytes = readFileSync(join(file.parentPath, file.name));
|
|
28
|
+
site[path] = entryOf(bytes, own ?? typeOf(path), own !== undefined, rewrite, host);
|
|
29
|
+
}
|
|
30
|
+
return site;
|
|
31
|
+
};
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { extname } from 'node:path';
|
|
2
|
+
// Content type by extension; an extension-less path is HTML, an unknown extension is bytes.
|
|
3
|
+
const TEXT_TYPES = {
|
|
4
|
+
'.html': 'text/html',
|
|
5
|
+
'.txt': 'text/plain',
|
|
6
|
+
'.md': 'text/markdown',
|
|
7
|
+
'.xml': 'application/xml',
|
|
8
|
+
'.json': 'application/json',
|
|
9
|
+
'.js': 'text/javascript',
|
|
10
|
+
'.mjs': 'text/javascript',
|
|
11
|
+
'.css': 'text/css',
|
|
12
|
+
'.svg': 'image/svg+xml',
|
|
13
|
+
'.webmanifest': 'application/manifest+json',
|
|
14
|
+
'.map': 'application/json',
|
|
15
|
+
};
|
|
16
|
+
export const TYPES = {
|
|
17
|
+
...TEXT_TYPES,
|
|
18
|
+
'.png': 'image/png',
|
|
19
|
+
'.jpg': 'image/jpeg',
|
|
20
|
+
'.jpeg': 'image/jpeg',
|
|
21
|
+
'.gif': 'image/gif',
|
|
22
|
+
'.webp': 'image/webp',
|
|
23
|
+
'.ico': 'image/x-icon',
|
|
24
|
+
'.mp4': 'video/mp4',
|
|
25
|
+
'.woff2': 'font/woff2',
|
|
26
|
+
'.woff': 'font/woff',
|
|
27
|
+
'.ttf': 'font/ttf',
|
|
28
|
+
'.avif': 'image/avif',
|
|
29
|
+
'.webm': 'video/webm',
|
|
30
|
+
};
|
|
31
|
+
const TEXT_APPLICATION = /^application\/(json|javascript|xml|manifest\+json)$|\+(json|xml)$/;
|
|
32
|
+
// A text type is read as a string (parameters like charset ignored); every other type as bytes.
|
|
33
|
+
export const isText = (type) => {
|
|
34
|
+
const media = (type.split(';')[0] ?? '').trim().toLowerCase();
|
|
35
|
+
return media.startsWith('text/') || TEXT_APPLICATION.test(media);
|
|
36
|
+
};
|
|
37
|
+
export const typeOf = (path) => {
|
|
38
|
+
const ext = extname(path);
|
|
39
|
+
return TYPES[ext] ?? (ext === '' ? 'text/html' : 'application/octet-stream');
|
|
40
|
+
};
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { type BuildInfo } from '../discovery/discovery.js';
|
|
2
2
|
export type Env = Readonly<Record<string, string | undefined>>;
|
|
3
3
|
export declare const isoSeconds: (date: Date) => string;
|
|
4
|
+
export declare const buildTimeOf: (env: Env, now: Date) => string;
|
|
4
5
|
export declare const buildInfoFromEnv: (env: Env, now?: Date) => BuildInfo;
|
|
5
6
|
export declare const portFromEnv: (env: Env, fallback?: number) => number;
|
|
@@ -3,10 +3,11 @@ import { FULL_SHA } from '../manifest/primitives.schema.js';
|
|
|
3
3
|
const UNKNOWN_COMMIT = '0'.repeat(40);
|
|
4
4
|
export const isoSeconds = (date) => `${date.toISOString().slice(0, 19)}Z`;
|
|
5
5
|
const commitOf = (sha = '') => (FULL_SHA.test(sha) ? sha : UNKNOWN_COMMIT);
|
|
6
|
+
export const buildTimeOf = (env, now) => env['BUILD_TIME'] || isoSeconds(now);
|
|
6
7
|
// COMMIT_SHA and BUILD_TIME are baked into every image by the recipe; a bare dev run shows zeros.
|
|
7
8
|
export const buildInfoFromEnv = (env, now = new Date()) => ({
|
|
8
9
|
commit: commitOf(env['COMMIT_SHA']),
|
|
9
|
-
buildTime: env
|
|
10
|
+
buildTime: buildTimeOf(env, now),
|
|
10
11
|
});
|
|
11
12
|
export const portFromEnv = (env, fallback = 3000) => {
|
|
12
13
|
const port = Number(env['PORT']);
|
|
@@ -6,9 +6,11 @@ import {} from '../manifest/manifest.schema.js';
|
|
|
6
6
|
import { loadCreate } from '../manifest/entry.js';
|
|
7
7
|
import { hasStore } from '../manifest/parts.js';
|
|
8
8
|
import {} from '../manifest/primitives.schema.js';
|
|
9
|
+
import { createSpan } from '../log/span.js';
|
|
9
10
|
import { createMcpApp } from '../mcp/mcp-app.js';
|
|
10
11
|
import { createToolRegistry } from '../mcp/tools.js';
|
|
11
12
|
import { createPagesApp, platformSources } from '../pages/pages-app.js';
|
|
13
|
+
import {} from '../pages/pages.js';
|
|
12
14
|
import { createApiApp, createPartApp } from '../server/app.js';
|
|
13
15
|
import { mountApi } from '../server/api-routes.js';
|
|
14
16
|
import {} from './build-info.js';
|
|
@@ -23,7 +25,7 @@ const api = async (input) => {
|
|
|
23
25
|
const { router, routes, documents } = await mountApi(ctx, (api) => callCreate(input, 'api', api));
|
|
24
26
|
// Declared routes guard at their own scope, whatever the committed file says.
|
|
25
27
|
const openapi = routes.length > 0 ? generatedOpenapi(input.pkg, routes) : input.openapi;
|
|
26
|
-
return { app: createApiApp({ ...input.base, router, openapi, wellKnown: documents }) };
|
|
28
|
+
return { app: createApiApp({ ...input.base, router, routes, openapi, wellKnown: documents }) };
|
|
27
29
|
};
|
|
28
30
|
const mcp = async (input) => {
|
|
29
31
|
const registry = createToolRegistry();
|
|
@@ -48,7 +50,12 @@ const worker = async (input) => {
|
|
|
48
50
|
const log = runLog(ctx.log);
|
|
49
51
|
const runs = hasStore(input.pkg, 'postgres') ? storeRuns(ctx.store) : memoryRuns();
|
|
50
52
|
const scheduler = createScheduler({ runs, log });
|
|
51
|
-
await callCreate(input, 'worker', {
|
|
53
|
+
await callCreate(input, 'worker', {
|
|
54
|
+
...ctx,
|
|
55
|
+
log,
|
|
56
|
+
span: createSpan(log),
|
|
57
|
+
schedule: scheduler.schedule,
|
|
58
|
+
});
|
|
52
59
|
const checks = { ...input.base.checks, ...scheduler.checks() };
|
|
53
60
|
scheduler.start();
|
|
54
61
|
return {
|
package/dist/runtime/run-part.js
CHANGED
|
@@ -4,7 +4,7 @@ import { readSecrets, SECRETS_DIR } from '../context/secrets.js';
|
|
|
4
4
|
import { settingsFromEnv } from '../context/settings.js';
|
|
5
5
|
import { DEFAULT_RECORD_FILE, loadRecord } from '../discovery/discovery.js';
|
|
6
6
|
import {} from '../discovery/discovery.schema.js';
|
|
7
|
-
import { declaredScopes, partAuth } from '../auth/part-auth.js';
|
|
7
|
+
import { declaredScopes, partAuth, platformOf } from '../auth/part-auth.js';
|
|
8
8
|
import { readOpenapi } from '../discovery/openapi.js';
|
|
9
9
|
import { createLog } from '../log/log.js';
|
|
10
10
|
import {} from '../manifest/entry.js';
|
|
@@ -42,6 +42,7 @@ const contextFor = (start, part, store) => createContext({
|
|
|
42
42
|
settings: settingsFromEnv(start.pkg, start.env, start.log),
|
|
43
43
|
store,
|
|
44
44
|
secrets: start.secrets,
|
|
45
|
+
platform: platformOf(start.env),
|
|
45
46
|
});
|
|
46
47
|
// Built on first use, so the ui runner, which never asks, has no ctx at all.
|
|
47
48
|
const lazyContext = (start, store) => {
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import { Router } from 'express';
|
|
2
|
+
import { inQuery } from '../api/openapi-doc.js';
|
|
2
3
|
import { createRouteRegistry } from '../api/routes.js';
|
|
3
4
|
import {} from '../api/well-known.js';
|
|
4
5
|
import {} from '../context/context.js';
|
|
5
6
|
import { isReply, ok, reply } from '../envelope/envelope.js';
|
|
6
7
|
import { parse } from '../envelope/parse.js';
|
|
7
8
|
import {} from './part.types.js';
|
|
8
|
-
const inQuery = (method) => method === 'get' || method === 'delete';
|
|
9
9
|
const inputOf = ({ method, spec }, query, body) => {
|
|
10
10
|
if (!spec.input)
|
|
11
11
|
return {};
|
|
@@ -16,14 +16,27 @@ const inputOf = ({ method, spec }, query, body) => {
|
|
|
16
16
|
// Validated in, the handler's data (bare or a reply) parsed by its output schema and sent in the envelope.
|
|
17
17
|
const handlerOf = (ctx, entry) => async (req, res) => {
|
|
18
18
|
const input = inputOf(entry, req.query, req.body);
|
|
19
|
+
const { query: shape } = entry.spec;
|
|
20
|
+
const query = shape ? parse(shape, req.query, 'Invalid query') : {};
|
|
19
21
|
const caller = ctx.auth.caller(req);
|
|
20
22
|
const { params: schema } = entry.spec;
|
|
21
23
|
const params = schema ? parse(schema, req.params, 'Invalid path') : req.params;
|
|
22
24
|
const ifMatch = req.get('if-match');
|
|
23
|
-
const answer = await entry.handler({
|
|
24
|
-
|
|
25
|
+
const answer = await entry.handler({
|
|
26
|
+
input,
|
|
27
|
+
query,
|
|
28
|
+
params,
|
|
29
|
+
caller,
|
|
30
|
+
ifMatch,
|
|
31
|
+
ip: req.ip ?? '',
|
|
32
|
+
header: (name) => req.get(name),
|
|
33
|
+
});
|
|
34
|
+
const { data, meta, etag, status = 200 } = isReply(answer) ? answer : reply(answer);
|
|
25
35
|
if (etag)
|
|
26
36
|
res.setHeader('ETag', etag);
|
|
37
|
+
if (status === 204)
|
|
38
|
+
return void res.status(204).end();
|
|
39
|
+
res.status(status);
|
|
27
40
|
res.json(ok(entry.spec.output ? entry.spec.output.parse(data) : data, meta));
|
|
28
41
|
};
|
|
29
42
|
// /items/{id} as Express writes it.
|
package/dist/server/app.d.ts
CHANGED
|
@@ -30,6 +30,10 @@ export interface ApiAppOptions extends PartAppBase {
|
|
|
30
30
|
router: ApiHandler;
|
|
31
31
|
openapi?: Record<string, unknown> | null;
|
|
32
32
|
wellKnown?: WellKnownEntry[];
|
|
33
|
+
routes?: {
|
|
34
|
+
method: string;
|
|
35
|
+
path: string;
|
|
36
|
+
}[];
|
|
33
37
|
}
|
|
34
38
|
export declare const PUBLIC_CORS: CorsOptions;
|
|
35
39
|
export declare const BODY_LIMIT = "1mb";
|
package/dist/server/app.js
CHANGED
|
@@ -3,7 +3,7 @@ import express, {} from 'express';
|
|
|
3
3
|
import helmet, {} from 'helmet';
|
|
4
4
|
import {} from '../api/well-known.js';
|
|
5
5
|
import { agcidMiddleware } from '../agcid/scope.js';
|
|
6
|
-
import { routeAccess } from '../auth/route-access.js';
|
|
6
|
+
import { routeAccess, sameShape } from '../auth/route-access.js';
|
|
7
7
|
import { setCaller } from '../auth/token-check.js';
|
|
8
8
|
import { discoveryDocument, recordOf, } from '../discovery/discovery.js';
|
|
9
9
|
import {} from '../discovery/discovery.schema.js';
|
|
@@ -18,7 +18,14 @@ import {} from './part.types.js';
|
|
|
18
18
|
export const PUBLIC_CORS = {
|
|
19
19
|
origin: '*',
|
|
20
20
|
credentials: false,
|
|
21
|
-
allowedHeaders: [
|
|
21
|
+
allowedHeaders: [
|
|
22
|
+
'Authorization',
|
|
23
|
+
'Content-Type',
|
|
24
|
+
'agcid',
|
|
25
|
+
'traceparent',
|
|
26
|
+
'If-Match',
|
|
27
|
+
'If-None-Match',
|
|
28
|
+
],
|
|
22
29
|
exposedHeaders: ['agcid', 'ETag', 'Retry-After', 'RateLimit', 'WWW-Authenticate'],
|
|
23
30
|
};
|
|
24
31
|
// api-standards section 5: parts take bearer tokens only, so no handler or log ever sees a cookie.
|
|
@@ -78,6 +85,10 @@ const wellKnownHandler = (render) => async (_req, res) => {
|
|
|
78
85
|
const routeGuard = (options) => async (req, res, next) => {
|
|
79
86
|
if (!options.tokenCheck)
|
|
80
87
|
return next();
|
|
88
|
+
const { routes } = options;
|
|
89
|
+
const known = routes?.some((r) => r.method === req.method.toLowerCase() && sameShape(r.path, req.path));
|
|
90
|
+
if (routes?.length && !known)
|
|
91
|
+
return next();
|
|
81
92
|
const access = routeAccess(options.openapi, req.method, `/api/v1${req.path}`);
|
|
82
93
|
const caller = await options.tokenCheck(req.get('authorization'), access);
|
|
83
94
|
if (caller)
|
|
@@ -43,7 +43,7 @@ export const startTestServer = async (options) => {
|
|
|
43
43
|
openapi: generatedOpenapi(pkg, mounted.routes),
|
|
44
44
|
};
|
|
45
45
|
const base = { pkg, build: TEST_BUILD, log: ctx.log, wellKnown: mounted.documents };
|
|
46
|
-
return startOn(createApiApp({ ...base, router: mounted.router, ...guard }));
|
|
46
|
+
return startOn(createApiApp({ ...base, router: mounted.router, routes: mounted.routes, ...guard }));
|
|
47
47
|
};
|
|
48
48
|
// Runs an mcp part's create(ctx) inside the kit's real /mcp app: tools named {id}__{name}.
|
|
49
49
|
export const startTestMcp = async (options) => {
|