@jimhoyd/urlcode 0.3.0 → 0.4.0-alpha.1
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/.claude/skills/urlcode-authoring/SKILL.md +106 -0
- package/.claude/skills/urlcode-operations/SKILL.md +114 -0
- package/.claude-plugin/marketplace.json +18 -0
- package/CONTRIBUTING.md +30 -2
- package/README.md +157 -230
- package/ROADMAP.md +85 -2
- package/SECURITY.md +8 -1
- package/dist/BUILD-MANIFEST.json +62 -32
- package/dist/adapters.js +4 -23
- package/dist/agent-lists.js +1 -1
- package/dist/agents-guide.js +113 -0
- package/dist/authoring-files.js +60 -0
- package/dist/authoring.js +11 -1
- package/dist/aws.js +4 -3
- package/dist/build-cloudflare.js +11 -24
- package/dist/bulk.js +37 -0
- package/dist/capabilities.js +208 -0
- package/dist/capability-query.js +72 -0
- package/dist/catalog.js +105 -0
- package/dist/cli.js +154 -15
- package/dist/client-address.js +1 -1
- package/dist/compliance-rules/baseline.js +8 -8
- package/dist/compliance-rules/privacy.js +3 -3
- package/dist/compliance-rules/strict.js +5 -5
- package/dist/conditions.js +88 -0
- package/dist/config.js +60 -4
- package/dist/context.js +156 -0
- package/dist/ecosystem-cli.js +88 -0
- package/dist/egress.js +98 -0
- package/dist/examples.js +92 -0
- package/dist/explain-cli.js +64 -0
- package/dist/explain.js +132 -0
- package/dist/extensions.js +172 -0
- package/dist/function-sources.js +15 -3
- package/dist/index.js +37 -0
- package/dist/init-with.js +165 -0
- package/dist/interchange-cli.js +42 -0
- package/dist/interchange.js +189 -0
- package/dist/link-cli.js +1 -1
- package/dist/management-policy.js +0 -1
- package/dist/manifest.js +111 -0
- package/dist/match.js +2 -2
- package/dist/mcp-authoring.js +147 -0
- package/dist/mcp.js +97 -0
- package/dist/observability.js +6 -0
- package/dist/operator-host.js +29 -0
- package/dist/plugins.js +12 -0
- package/dist/policies/agents.js +2 -2
- package/dist/policies/compression.js +2 -1
- package/dist/policies/security.js +0 -0
- package/dist/policies.js +1 -1
- package/dist/policy.js +29 -7
- package/dist/prerender.js +100 -41
- package/dist/project-tests.js +3 -3
- package/dist/provider-verification.js +92 -0
- package/dist/proxy.js +44 -0
- package/dist/readiness.js +5 -5
- package/dist/recipes.js +41 -0
- package/dist/route-diff.js +106 -0
- package/dist/router.js +42 -2
- package/dist/runtime.js +95 -14
- package/dist/schema-query.js +62 -0
- package/dist/signals.js +24 -0
- package/dist/site.js +0 -0
- package/dist/tooling.js +96 -0
- package/dist/types/adapters.d.ts +7 -4
- package/dist/types/agent-lists.d.ts +0 -1
- package/dist/types/agents-guide.d.ts +17 -0
- package/dist/types/authoring-files.d.ts +10 -0
- package/dist/types/aws.d.ts +3 -1
- package/dist/types/build-cloudflare.d.ts +1 -0
- package/dist/types/bulk.d.ts +27 -0
- package/dist/types/capabilities.d.ts +55 -0
- package/dist/types/capability-query.d.ts +24 -0
- package/dist/types/catalog.d.ts +65 -0
- package/dist/types/client-address.d.ts +0 -1
- package/dist/types/compliance-rules/baseline.d.ts +1 -9
- package/dist/types/compliance-rules/privacy.d.ts +1 -4
- package/dist/types/compliance-rules/strict.d.ts +0 -5
- package/dist/types/conditions.d.ts +19 -0
- package/dist/types/config.d.ts +20 -2
- package/dist/types/context.d.ts +65 -0
- package/dist/types/ecosystem-cli.d.ts +17 -0
- package/dist/types/egress.d.ts +46 -0
- package/dist/types/examples.d.ts +50 -0
- package/dist/types/explain-cli.d.ts +11 -0
- package/dist/types/explain.d.ts +95 -0
- package/dist/types/extensions.d.ts +122 -0
- package/dist/types/function-sources.d.ts +5 -0
- package/dist/types/index.d.ts +33 -0
- package/dist/types/init-with.d.ts +30 -0
- package/dist/types/interchange-cli.d.ts +16 -0
- package/dist/types/interchange.d.ts +42 -0
- package/dist/types/link-cli.d.ts +2 -1
- package/dist/types/management-policy.d.ts +0 -1
- package/dist/types/manifest.d.ts +81 -0
- package/dist/types/match.d.ts +1 -0
- package/dist/types/mcp-authoring.d.ts +92 -0
- package/dist/types/mcp.d.ts +12 -0
- package/dist/types/observability.d.ts +2 -0
- package/dist/types/operator-host.d.ts +8 -0
- package/dist/types/plugins.d.ts +2 -0
- package/dist/types/policies/agents.d.ts +0 -2
- package/dist/types/policies/compression.d.ts +2 -0
- package/dist/types/policies/security.d.ts +0 -1
- package/dist/types/policy.d.ts +15 -4
- package/dist/types/project-tests.d.ts +3 -1
- package/dist/types/provider-verification.d.ts +53 -0
- package/dist/types/proxy.d.ts +21 -0
- package/dist/types/readiness.d.ts +1 -1
- package/dist/types/recipes.d.ts +30 -0
- package/dist/types/route-diff.d.ts +27 -0
- package/dist/types/runtime.d.ts +11 -0
- package/dist/types/schema-query.d.ts +12 -0
- package/dist/types/signals.d.ts +25 -0
- package/dist/types/site.d.ts +0 -1
- package/dist/types/tooling.d.ts +115 -0
- package/dist/types/types.d.ts +57 -0
- package/dist/types/typescript-authoring.d.ts +12 -0
- package/dist/types/vercel.d.ts +3 -1
- package/dist/types/verify-deployment.d.ts +47 -0
- package/dist/types.js +21 -2
- package/dist/typescript-authoring.js +104 -0
- package/dist/vercel.js +4 -3
- package/dist/verify-deployment.js +270 -0
- package/docs/AI-AUTHORING.md +130 -8
- package/docs/BULK.md +79 -0
- package/docs/CAPABILITIES.md +179 -0
- package/docs/CAPACITY.md +1 -1
- package/docs/CI.md +142 -0
- package/docs/CONDITIONS.md +74 -0
- package/docs/DEPLOYMENT-CHECKS.md +108 -0
- package/docs/DYNAMIC-LINKS.md +18 -518
- package/docs/EGRESS.md +125 -0
- package/docs/EXTENSIONS.md +226 -0
- package/docs/FRAMEWORK.md +182 -0
- package/docs/INSTALL.md +45 -7
- package/docs/INTERCHANGE.md +134 -0
- package/docs/MIDDLEWARE-EXAMPLES.md +75 -0
- package/docs/MIDDLEWARE.md +2 -0
- package/docs/NEXT-PHASE-PLAN.md +90 -0
- package/docs/NEXT-STEPS.md +415 -0
- package/docs/OBSERVABILITY.md +4 -2
- package/docs/OPERATIONAL-PROOF.md +4 -1
- package/docs/OPERATIONS.md +6 -3
- package/docs/PLUGINS.md +37 -0
- package/docs/POLICIES.md +12 -309
- package/docs/PRERENDER.md +40 -0
- package/docs/PROJECT-DIRECTION.md +42 -0
- package/docs/PROVIDER-VERIFICATION.md +84 -0
- package/docs/READINESS.md +21 -1
- package/docs/README.md +82 -31
- package/docs/RECIPES.md +99 -0
- package/docs/RELEASE-READINESS.md +11 -9
- package/docs/RELEASE-SECURITY.md +27 -4
- package/docs/SECURITY-AUDIT.md +1 -1
- package/docs/SPECIFICATION.md +95 -8
- package/docs/SPIKE-BUSINESS-SUITE.md +1013 -0
- package/docs/SPIKE-EXTENSION-MODEL.md +419 -0
- package/docs/SPIKE-EXTENSIONS.md +1 -0
- package/docs/SPIKE-LAMBDA-COMPILE.md +199 -0
- package/docs/STANDARDS.md +150 -142
- package/docs/STARTERS.md +21 -1
- package/docs/TOOLING.md +291 -0
- package/docs/TYPESCRIPT-AUTHORING.md +67 -0
- package/docs/TYPESCRIPT.md +1 -1
- package/docs/USABILITY-REVIEW.md +123 -0
- package/docs/YAML-GUIDE.md +18 -479
- package/docs/YAML-REFERENCE.md +127 -16
- package/docs/links/cli.md +110 -0
- package/docs/links/limits.md +175 -0
- package/docs/links/management-api.md +80 -0
- package/docs/links/pools.md +75 -0
- package/docs/links/setup.md +135 -0
- package/docs/policies/agents.md +1 -1
- package/docs/policies/contract.md +52 -0
- package/docs/policies/hardened.md +56 -0
- package/docs/policies/interoperability.md +169 -0
- package/docs/policies/operations.md +45 -0
- package/docs/yaml/assets.md +36 -0
- package/docs/yaml/conditions.md +20 -0
- package/docs/yaml/functions.md +160 -0
- package/docs/yaml/links.md +30 -0
- package/docs/yaml/middleware.md +29 -0
- package/docs/yaml/organization.md +74 -0
- package/docs/yaml/policies.md +37 -0
- package/docs/yaml/redirects.md +64 -0
- package/docs/yaml/responses.md +57 -0
- package/docs/yaml/site.md +24 -0
- package/examples/assets/example.yaml +17 -0
- package/examples/aws/example.yaml +20 -0
- package/examples/cloudflare/example.yaml +19 -0
- package/examples/compliance/example.yaml +11 -0
- package/examples/conditions/README.md +12 -0
- package/examples/conditions/example.yaml +19 -0
- package/examples/conditions/tests/requests.json +13 -0
- package/examples/conditions/urlcode.yaml +24 -0
- package/examples/cookbook/README.md +8 -4
- package/examples/cookbook/example.yaml +17 -0
- package/examples/cookbook/functions/catalog.mjs +3 -0
- package/examples/cookbook/functions/fail.mjs +4 -0
- package/examples/cookbook/functions/items.mjs +3 -0
- package/examples/cookbook/functions/profile.mjs +3 -0
- package/examples/cookbook/functions/resource.mjs +3 -0
- package/examples/cookbook/functions/status.mjs +3 -0
- package/examples/cookbook/middleware/auth.mjs +48 -0
- package/examples/cookbook/middleware/body.mjs +15 -0
- package/examples/cookbook/middleware/bucket.mjs +19 -0
- package/examples/cookbook/middleware/cors.mjs +21 -0
- package/examples/cookbook/middleware/debug.mjs +13 -0
- package/examples/cookbook/middleware/envelope.mjs +11 -0
- package/examples/cookbook/middleware/errors.mjs +11 -0
- package/examples/cookbook/middleware/etag.mjs +18 -0
- package/examples/cookbook/middleware/locale.mjs +16 -0
- package/examples/cookbook/middleware/maintenance.mjs +10 -0
- package/examples/cookbook/middleware/methods.mjs +15 -0
- package/examples/cookbook/middleware/negotiate.mjs +20 -0
- package/examples/cookbook/middleware/referer.mjs +12 -0
- package/examples/cookbook/middleware/request-id.mjs +16 -0
- package/examples/cookbook/route-index.json +676 -0
- package/examples/cookbook/routes/middleware.yaml +126 -0
- package/examples/cookbook/tests/requests.json +526 -0
- package/examples/cookbook/urlcode.yaml +1 -0
- package/examples/egress/README.md +22 -0
- package/examples/egress/example.yaml +19 -0
- package/examples/egress/urlcode.yaml +19 -0
- package/examples/extensions/README.md +7 -0
- package/examples/extensions/example.yaml +21 -0
- package/examples/extensions/urlcode.yaml +25 -0
- package/examples/live-links/example.yaml +21 -0
- package/examples/monitoring/example.yaml +8 -0
- package/examples/prerender/example.yaml +16 -0
- package/examples/provider-conformance/README.md +12 -0
- package/examples/provider-conformance/example.yaml +14 -0
- package/examples/provider-conformance/urlcode.yaml +34 -0
- package/examples/tunnel/example.yaml +8 -0
- package/examples/vercel/example.yaml +19 -0
- package/llms-full.txt +2709 -0
- package/llms.txt +48 -19
- package/package.json +29 -7
- package/packaging/claude-plugin/.claude-plugin/plugin.json +19 -0
- package/packaging/claude-plugin/skills/urlcode-authoring/SKILL.md +106 -0
- package/packaging/claude-plugin/skills/urlcode-operations/SKILL.md +114 -0
- package/recipes/authenticated-json-api/README.md +51 -0
- package/recipes/authenticated-json-api/functions/profile.mjs +5 -0
- package/recipes/authenticated-json-api/recipe.yaml +34 -0
- package/recipes/authenticated-json-api/tests/requests.json +39 -0
- package/recipes/authenticated-json-api/urlcode.yaml +12 -0
- package/recipes/contact-form/README.md +25 -0
- package/recipes/contact-form/functions/contact.mjs +17 -0
- package/recipes/contact-form/recipe.yaml +33 -0
- package/recipes/contact-form/tests/requests.json +47 -0
- package/recipes/contact-form/urlcode.yaml +18 -0
- package/recipes/cors-api/README.md +16 -0
- package/recipes/cors-api/functions/items.mjs +3 -0
- package/recipes/cors-api/middleware/cors.mjs +21 -0
- package/recipes/cors-api/recipe.yaml +26 -0
- package/recipes/cors-api/tests/requests.json +65 -0
- package/recipes/cors-api/urlcode.yaml +12 -0
- package/recipes/health-page/README.md +13 -0
- package/recipes/health-page/recipe.yaml +23 -0
- package/recipes/health-page/tests/requests.json +36 -0
- package/recipes/health-page/urlcode.yaml +19 -0
- package/recipes/json-api/README.md +6 -0
- package/recipes/json-api/functions/echo.mjs +3 -0
- package/recipes/json-api/recipe.yaml +25 -0
- package/recipes/json-api/tests/requests.json +34 -0
- package/recipes/json-api/urlcode.yaml +12 -0
- package/recipes/middleware/README.md +34 -0
- package/recipes/middleware/functions/catalog.mjs +3 -0
- package/recipes/middleware/functions/fail.mjs +4 -0
- package/recipes/middleware/functions/items.mjs +3 -0
- package/recipes/middleware/functions/profile.mjs +3 -0
- package/recipes/middleware/functions/resource.mjs +3 -0
- package/recipes/middleware/functions/status.mjs +3 -0
- package/recipes/middleware/middleware/auth.mjs +48 -0
- package/recipes/middleware/middleware/body.mjs +15 -0
- package/recipes/middleware/middleware/bucket.mjs +19 -0
- package/recipes/middleware/middleware/cors.mjs +21 -0
- package/recipes/middleware/middleware/debug.mjs +13 -0
- package/recipes/middleware/middleware/envelope.mjs +11 -0
- package/recipes/middleware/middleware/errors.mjs +11 -0
- package/recipes/middleware/middleware/etag.mjs +18 -0
- package/recipes/middleware/middleware/locale.mjs +16 -0
- package/recipes/middleware/middleware/maintenance.mjs +10 -0
- package/recipes/middleware/middleware/methods.mjs +15 -0
- package/recipes/middleware/middleware/negotiate.mjs +20 -0
- package/recipes/middleware/middleware/referer.mjs +12 -0
- package/recipes/middleware/middleware/request-id.mjs +16 -0
- package/recipes/middleware/public/guide.txt +1 -0
- package/recipes/middleware/recipe.yaml +50 -0
- package/recipes/middleware/tests/requests.json +528 -0
- package/recipes/middleware/urlcode.yaml +127 -0
- package/recipes/protected-download/README.md +22 -0
- package/recipes/protected-download/files/report.txt +1 -0
- package/recipes/protected-download/recipe.yaml +31 -0
- package/recipes/protected-download/tests/requests.json +32 -0
- package/recipes/protected-download/urlcode.yaml +15 -0
- package/recipes/redirect/README.md +7 -0
- package/recipes/redirect/recipe.yaml +25 -0
- package/recipes/redirect/tests/requests.json +19 -0
- package/recipes/redirect/urlcode.yaml +9 -0
- package/recipes/static-plus-api/README.md +15 -0
- package/recipes/static-plus-api/functions/info.mjs +3 -0
- package/recipes/static-plus-api/public/assets/index.html +3 -0
- package/recipes/static-plus-api/public/assets/site.css +1 -0
- package/recipes/static-plus-api/public/index.html +8 -0
- package/recipes/static-plus-api/recipe.yaml +29 -0
- package/recipes/static-plus-api/tests/requests.json +56 -0
- package/recipes/static-plus-api/urlcode.yaml +23 -0
- package/recipes/typescript/README.md +7 -0
- package/recipes/typescript/functions/hello.ts +5 -0
- package/recipes/typescript/recipe.yaml +23 -0
- package/recipes/typescript/tests/requests.json +18 -0
- package/recipes/typescript/urlcode.yaml +5 -0
- package/recipes/webhook-receiver/README.md +16 -0
- package/recipes/webhook-receiver/functions/receive.mjs +16 -0
- package/recipes/webhook-receiver/recipe.yaml +26 -0
- package/recipes/webhook-receiver/tests/requests.json +59 -0
- package/recipes/webhook-receiver/urlcode.yaml +16 -0
- package/schemas/recipe.schema.json +138 -0
- package/schemas/urlcode.schema.json +656 -80
- package/skills/urlcode/SKILL.md +98 -0
- package/starters/default/.github/workflows/urlcode.yml +23 -0
- package/starters/default/.mcp.json +12 -0
- package/starters/default/AGENTS.md +79 -0
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import {realpath,readdir,mkdtemp,rm} from 'node:fs/promises';
|
|
2
|
+
import {join,posix} from 'node:path';
|
|
3
|
+
import {tmpdir} from 'node:os';
|
|
4
|
+
|
|
5
|
+
import {init,parse} from 'es-module-lexer';
|
|
6
|
+
import {stringify} from 'yaml';
|
|
7
|
+
import {loadDocument} from './config.js';
|
|
8
|
+
import {collectFunctionSources,routeFunctions} from './function-sources.js';
|
|
9
|
+
import {authoringPath,authoringFile,readAuthoringFile,publishAuthoringProject} from './authoring-files.js';
|
|
10
|
+
import {assert} from './errors.js';
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
const emitted=(path )=>path.replace(/\.ts$/,'.js');
|
|
14
|
+
|
|
15
|
+
/** Transpile a project snapshot ahead of runtime. No project compiler settings,
|
|
16
|
+
* plugins, package resolution, subprocesses or guest code execution are used. */
|
|
17
|
+
export async function buildTypeScriptProject(project ,output ,{dryRun=false} ={}) {
|
|
18
|
+
const root=await realpath(project),loaded=await loadDocument(root),files=new Map (),modules=new Map ();
|
|
19
|
+
const {default:ts}=await import('typescript');
|
|
20
|
+
let sourceBytes=0,assetBytes=0;
|
|
21
|
+
await init;
|
|
22
|
+
async function collect(path ) {
|
|
23
|
+
authoringPath(path);assert(/\.(?:ts|js|mjs)$/.test(path) && !path.endsWith('.d.ts'),'Guest source must be .ts, .js or .mjs');
|
|
24
|
+
if(modules.has(path))return;
|
|
25
|
+
assert(modules.size<128,'Function module limit exceeded');
|
|
26
|
+
const bytes=await readAuthoringFile(root,path,1048576);sourceBytes+=bytes.length;
|
|
27
|
+
assert(sourceBytes<=4194304,'Function source limit exceeded');
|
|
28
|
+
const source=new TextDecoder('utf-8',{fatal:true}).decode(bytes);
|
|
29
|
+
modules.set(path,emitted(path));
|
|
30
|
+
let code=source;
|
|
31
|
+
if(path.endsWith('.ts')){
|
|
32
|
+
const ast=ts.createSourceFile(path,source,ts.ScriptTarget.ES2022,true,ts.ScriptKind.TS);
|
|
33
|
+
// Bare imports are forbidden even if they would be erased as type-only.
|
|
34
|
+
const inspect=(node ) =>{
|
|
35
|
+
assert(!ts.isImportEqualsDeclaration(node) && !(ts.isExportAssignment(node) && node.isExportEquals),'CommonJS TypeScript module syntax is unsupported');
|
|
36
|
+
if((ts.isImportDeclaration(node)||ts.isExportDeclaration(node)) && node.moduleSpecifier){
|
|
37
|
+
assert(ts.isStringLiteral(node.moduleSpecifier),'Only literal relative imports are supported');
|
|
38
|
+
const name=node.moduleSpecifier.text;
|
|
39
|
+
assert((name.startsWith('./')||name.startsWith('../')) && /\.(?:ts|js|mjs)$/.test(name),'Only relative guest module imports are supported');
|
|
40
|
+
}
|
|
41
|
+
ts.forEachChild(node,inspect);
|
|
42
|
+
};
|
|
43
|
+
inspect(ast);
|
|
44
|
+
const result=ts.transpileModule(source,{fileName:path,reportDiagnostics:true,compilerOptions:{
|
|
45
|
+
target:ts.ScriptTarget.ES2022,module:ts.ModuleKind.ESNext,isolatedModules:true,verbatimModuleSyntax:true,
|
|
46
|
+
sourceMap:false,inlineSourceMap:false,removeComments:false,
|
|
47
|
+
}});
|
|
48
|
+
assert(!result.diagnostics?.some(d=>d.category===ts.DiagnosticCategory.Error),'Invalid TypeScript guest source');
|
|
49
|
+
code=result.outputText;
|
|
50
|
+
}
|
|
51
|
+
const [imports]=parse(code);const edits =[];
|
|
52
|
+
for(const item of imports){
|
|
53
|
+
assert(item.type==='static' && typeof item.specifier==='string' && !item.attributes && !item.phase,'Dynamic imports and import.meta are unsupported in sandbox functions');
|
|
54
|
+
assert(item.specifier.startsWith('./')||item.specifier.startsWith('../'),'Only relative guest module imports are supported');
|
|
55
|
+
assert(!/[\\\u0000-\u001f]/u.test(item.specifier),'Invalid guest import path');
|
|
56
|
+
const dependency=posix.normalize(posix.join(posix.dirname(path),item.specifier));
|
|
57
|
+
await collect(dependency);
|
|
58
|
+
edits.push({start:item.start-1,end:item.end+1,value:JSON.stringify(emitted(item.specifier))});
|
|
59
|
+
}
|
|
60
|
+
for(const edit of edits.sort((a,b)=>b.start-a.start))code=code.slice(0,edit.start)+edit.value+code.slice(edit.end);
|
|
61
|
+
const target=emitted(path);assert(!files.has(target),'Guest output module collision');files.set(target,code);
|
|
62
|
+
}
|
|
63
|
+
for(const route of Object.values(loaded.routes))for(const definition of routeFunctions(route)){
|
|
64
|
+
await collect(definition.source);definition.source=emitted(definition.source);
|
|
65
|
+
}
|
|
66
|
+
async function asset(path ) {
|
|
67
|
+
if(files.has(path))return;assert(files.size<10000,'Authoring file limit exceeded');
|
|
68
|
+
const bytes=await readAuthoringFile(root,path,16*1048576);assetBytes+=bytes.length;
|
|
69
|
+
assert(assetBytes<=64*1048576,'Authoring asset limit exceeded');files.set(path,bytes);
|
|
70
|
+
}
|
|
71
|
+
async function directory(path ) {
|
|
72
|
+
const absolute=await authoringFile(root,path,true);
|
|
73
|
+
const entries=await readdir(absolute,{withFileTypes:true});
|
|
74
|
+
assert(entries.length>0,'Empty static directories need an asset before authoring build');
|
|
75
|
+
for(const entry of entries){
|
|
76
|
+
const child=path+'/'+entry.name;authoringPath(child);
|
|
77
|
+
assert(!entry.isSymbolicLink(),'Authoring through symlinks is forbidden');
|
|
78
|
+
if(entry.isDirectory())await directory(child);else await asset(child);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
for(const route of Object.values(loaded.routes)){
|
|
82
|
+
for(const ref of [route.page,route.download])if(ref)await asset(ref.file);
|
|
83
|
+
if(route.static)await directory(route.static.directory);
|
|
84
|
+
}
|
|
85
|
+
for(const ref of [loaded.document.site?.favicon,loaded.document.site?.llms])if(ref)await asset(ref);
|
|
86
|
+
// Request fixtures describe behavior the emitted project must keep, so they travel with it.
|
|
87
|
+
try{await asset('tests/requests.json');}catch(error){if(!(error instanceof Error && 'code' in error && error.code==='ENOENT'))throw error;}
|
|
88
|
+
// Flatten includes using the loader's duplicate-checked route table. Original
|
|
89
|
+
// project metadata stays in the entry; executable sources are the only edits.
|
|
90
|
+
const document={...loaded.document,routes:loaded.routes};delete document.includes;
|
|
91
|
+
assert(!files.has('urlcode.yaml'),'Guest source conflicts with entry configuration');
|
|
92
|
+
files.set('urlcode.yaml',stringify(document));
|
|
93
|
+
// Reuse the exact runtime module parser/path/source-budget validation on the
|
|
94
|
+
// emitted snapshot before touching the requested destination.
|
|
95
|
+
const temporary=await mkdtemp(join(tmpdir(),'urlcode-ts-'));
|
|
96
|
+
try {
|
|
97
|
+
const validation=await publishAuthoringProject(join(temporary,'project'),files);
|
|
98
|
+
await collectFunctionSources(Object.values(loaded.routes).map(route=>({
|
|
99
|
+
middleware:(route.middleware||[]).map(def=>({source:join(validation,def.source),export:def.export||'default'})),
|
|
100
|
+
...(route.function?{function:{source:join(validation,route.function.source),export:route.function.export||'default'}}:{}),
|
|
101
|
+
})),validation);
|
|
102
|
+
}finally{await rm(temporary,{recursive:true,force:true});}
|
|
103
|
+
return {output:await publishAuthoringProject(output,files,dryRun),dryRun,modules:[...modules.values()].sort(),files:[...files.keys()].sort(),typeChecked:false};
|
|
104
|
+
}
|
package/dist/vercel.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
|
|
1
2
|
import { randomUUID } from 'node:crypto';
|
|
2
3
|
|
|
3
4
|
import { activateNativeOnly, lazyRuntime, resolveOrigin } from './adapters.js';
|
|
@@ -6,7 +7,7 @@ import { activateNativeOnly, lazyRuntime, resolveOrigin } from './adapters.js';
|
|
|
6
7
|
import { writeResponse, writeError } from './http-response.js';
|
|
7
8
|
import { assert, HttpError } from './errors.js';
|
|
8
9
|
|
|
9
|
-
|
|
10
|
+
|
|
10
11
|
|
|
11
12
|
|
|
12
13
|
const platformOrigins = ['VERCEL_PROJECT_PRODUCTION_URL','VERCEL_URL','VERCEL_BRANCH_URL'];
|
|
@@ -31,9 +32,9 @@ function readBody(req , limit ) {
|
|
|
31
32
|
// instance and reused across warm invocations; a failed activation is not
|
|
32
33
|
// cached, so a fixed deployment recovers without a code change.
|
|
33
34
|
export function createVercelHandler({ project = process.cwd(), origin, environment = process.env,
|
|
34
|
-
maxBodyBytes = 1048576, plugins } = {}) {
|
|
35
|
+
maxBodyBytes = 1048576, plugins, extensions } = {}) {
|
|
35
36
|
assert(Number.isInteger(maxBodyBytes) && maxBodyBytes >= 1 && maxBodyBytes <= 16777216, 'Request limit must be 1–16777216 bytes');
|
|
36
|
-
const ready = lazyRuntime(() => activateNativeOnly(project, environment, { target: 'vercel', plugins }));
|
|
37
|
+
const ready = lazyRuntime(() => activateNativeOnly(project, environment, { target: 'vercel', plugins, extensions, origin:resolveOrigin(origin,environment,platformOrigins) }));
|
|
37
38
|
|
|
38
39
|
return async function handler(req,res) {
|
|
39
40
|
const requestId = randomUUID();
|
|
@@ -0,0 +1,270 @@
|
|
|
1
|
+
import { request, Agent } from 'node:http';
|
|
2
|
+
|
|
3
|
+
import { request as secureRequest, Agent as SecureAgent } from 'node:https';
|
|
4
|
+
import { randomBytes } from 'node:crypto';
|
|
5
|
+
import { assert } from './errors.js';
|
|
6
|
+
import { createRuntime } from './runtime.js';
|
|
7
|
+
|
|
8
|
+
import { benchmarkTarget, hit, readCases, probeAgent } from './readiness.js';
|
|
9
|
+
|
|
10
|
+
import { runCompliance, severities } from './compliance.js';
|
|
11
|
+
|
|
12
|
+
import { loadDocument } from './config.js';
|
|
13
|
+
import { applySite } from './site.js';
|
|
14
|
+
import { effectivePolicies, compileErrorPolicy, errorHeaders } from './policies.js';
|
|
15
|
+
import * as security from './policies/security.js';
|
|
16
|
+
import { DEFAULT_TYPES as compressibleTypes } from './policies/compression.js';
|
|
17
|
+
import { lists as bundledAgents } from '../data/agents/index.js';
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
// Deployment verification: does the running deployment behind `--target`
|
|
22
|
+
// match what this project declares? Everything here is inferred from HTTP
|
|
23
|
+
// responses to a bounded set of requests. There is no infrastructure access,
|
|
24
|
+
// no credential and no `--insecure`: a certificate Node rejects is a finding,
|
|
25
|
+
// not an option. A passing run says the deployment answers the way the local
|
|
26
|
+
// snapshot would; it says nothing about the host, the proxy or the network.
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
export const failLevels = Object.freeze([...severities, 'none']);
|
|
44
|
+
const CONCURRENCY = 4;
|
|
45
|
+
const MAX_REQUESTS = 10000;
|
|
46
|
+
const BODY_LIMIT = 1048576;
|
|
47
|
+
const SNIPPET = 200;
|
|
48
|
+
const siteTypes = { 'site.robots': 'text/plain', 'site.sitemap': 'application/xml', 'site.securityTxt': 'text/plain', 'site.llms': 'text/plain' };
|
|
49
|
+
const isRecord = (value ) => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
50
|
+
const snippet = (body ) => body.length > SNIPPET ? `${body.length} bytes: ${body.subarray(0, SNIPPET).toString('utf8')}` : body.toString('utf8');
|
|
51
|
+
const tlsCode = /CERT|TLS|SSL|SELF_SIGNED/;
|
|
52
|
+
|
|
53
|
+
// One request, one answer. Bodies are read up to 1 MiB and never logged
|
|
54
|
+
// beyond the snippet a failing assertion carries. Redirects are not followed
|
|
55
|
+
// and a transport error is reported as text, never thrown.
|
|
56
|
+
function probe(target , { path, method = 'GET', headers = {} } , agent , timeoutMs ) {
|
|
57
|
+
return new Promise(resolve => {
|
|
58
|
+
const fail = (error ) => {
|
|
59
|
+
const code = isRecord(error) && typeof error.code === 'string' ? error.code : error instanceof Error ? error.message : 'transport';
|
|
60
|
+
resolve({ status: 0, headers: {}, body: Buffer.alloc(0), error: code });
|
|
61
|
+
};
|
|
62
|
+
let req ;
|
|
63
|
+
try {
|
|
64
|
+
const options = { host: target.hostname, port: target.port, path, method, agent, timeout: timeoutMs,
|
|
65
|
+
headers: { host: target.hostname, 'user-agent': probeAgent, 'accept-encoding': 'identity', ...headers } };
|
|
66
|
+
req = (target.protocol === 'https:' ? secureRequest : request)(options, (res ) => {
|
|
67
|
+
const chunks = []; let size = 0;
|
|
68
|
+
res.on('data', (chunk ) => { if (size < BODY_LIMIT) chunks.push(chunk); size += chunk.length; });
|
|
69
|
+
res.on('error', fail);
|
|
70
|
+
res.on('end', () => {
|
|
71
|
+
const out = {};
|
|
72
|
+
for (const [key, value] of Object.entries(res.headers)) if (value !== undefined) out[key] = Array.isArray(value) ? value.join(', ') : value;
|
|
73
|
+
resolve({ status: res.statusCode ?? 0, headers: out, body: Buffer.concat(chunks) });
|
|
74
|
+
});
|
|
75
|
+
});
|
|
76
|
+
req.on('error', fail); req.on('timeout', () => req?.destroy(new Error('timeout'))); req.end();
|
|
77
|
+
} catch (error) { req?.destroy(); fail(error); }
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
async function each (items , fn ) {
|
|
82
|
+
let next = 0;
|
|
83
|
+
await Promise.all(Array.from({ length: Math.min(CONCURRENCY, items.length) }, async () => { while (next < items.length) await fn(items[next++] ); }));
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// The security headers a response on `pattern` must carry: the profile minus
|
|
87
|
+
// unset, plus set, with a YAML response header keeping its declared value on
|
|
88
|
+
// a success (the runtime applies YAML headers before the profile fills gaps;
|
|
89
|
+
// a 405 or an error never gets them). HSTS follows the origin, so an https
|
|
90
|
+
// target expects it and an http target does not.
|
|
91
|
+
function expectedSecurity(config , pattern , route , origin , status ) {
|
|
92
|
+
const state = security.compile(config, { route: { pattern } });
|
|
93
|
+
const declared = status < 400 ? Object.entries(route.response?.headers ?? {}).flatMap(([key, value]) => typeof value === 'string' ? [[key.toLowerCase(), value] ] : []) : [];
|
|
94
|
+
const keys = new Set([...state.profile.map(([key]) => key), ...state.overrideKeys]);
|
|
95
|
+
return security.onResponse(state, { origin }, { status, headers: declared }).headers.filter(([key]) => keys.has(key.toLowerCase()));
|
|
96
|
+
}
|
|
97
|
+
const mediaMatches = (types , header ) => {
|
|
98
|
+
const type = (header ?? '').split(';')[0] .trim().toLowerCase();
|
|
99
|
+
return Boolean(type) && types.some(candidate => candidate.endsWith('/*') ? type.startsWith(candidate.slice(0, -1).toLowerCase()) : type === candidate.toLowerCase());
|
|
100
|
+
};
|
|
101
|
+
// A User-Agent the bundled deny lists must refuse: the first entry of the
|
|
102
|
+
// first bundled deny list that no bundled allow list also matches.
|
|
103
|
+
function deniedAgent(agents ) {
|
|
104
|
+
const allow = (agents?.allow ?? []).flatMap(list => bundledAgents[list.name]?.patterns.map(([, pattern]) => new RegExp(pattern, 'i')) ?? []);
|
|
105
|
+
for (const list of agents?.deny ?? []) {
|
|
106
|
+
for (const [entry, pattern] of bundledAgents[list.name]?.patterns ?? []) {
|
|
107
|
+
const agent = `Mozilla/5.0 (compatible; ${entry})`;
|
|
108
|
+
if (new RegExp(pattern, 'i').test(agent) && !allow.some(re => re.test(agent))) return agent;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
return undefined;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export async function verifyDeployment(project , { target, origin, expectRoutes, timeoutMs = 10000, expectMetrics = false, failOn = 'high', compliance, complianceWarn = false, log = () => {}, permissions, linkStore } ) {
|
|
115
|
+
const destination = benchmarkTarget(target);
|
|
116
|
+
const targetOrigin = target.replace(/\/$/, '');
|
|
117
|
+
assert(failLevels.includes(failOn), `Use --fail-on ${failLevels.join('|')}`);
|
|
118
|
+
assert(Number.isInteger(timeoutMs) && timeoutMs >= 100 && timeoutMs <= 120000, 'Timeout must be 100-120000 ms');
|
|
119
|
+
assert(expectRoutes === undefined || (Number.isSafeInteger(expectRoutes) && expectRoutes >= 0), 'Expected route count must be an integer');
|
|
120
|
+
const publicOrigin = origin ?? targetOrigin;
|
|
121
|
+
const findings = [], notes = [];
|
|
122
|
+
let checks = 0, requests = 0;
|
|
123
|
+
const check = (ok , finding ) => { checks++; if (!ok) { findings.push(finding); log({ event: 'finding', ...finding }); } return ok; };
|
|
124
|
+
const agent = destination.protocol === 'https:' ? new SecureAgent({ keepAlive: true, maxSockets: CONCURRENCY }) : new Agent({ keepAlive: true, maxSockets: CONCURRENCY });
|
|
125
|
+
const send = async (p ) => { requests++; return probe(destination, p, agent, timeoutMs); };
|
|
126
|
+
// The local snapshot is the declaration: its version, its plan, its policies.
|
|
127
|
+
const runtime = await createRuntime(project, { local: true, origin: publicOrigin, permissions, linkStore, log: () => {} });
|
|
128
|
+
const version = { local: runtime.version, observed: null };
|
|
129
|
+
const routes = { local: runtime.count, observed: null, expected: expectRoutes ?? null };
|
|
130
|
+
let complianceReport = null;
|
|
131
|
+
try {
|
|
132
|
+
const plan = runtime.testPlan(), fixtures = await readCases(runtime.root, true);
|
|
133
|
+
const loaded = await loadDocument(runtime.root);
|
|
134
|
+
await applySite(loaded, { origin: publicOrigin, log: () => {} });
|
|
135
|
+
const cases = [...plan.cases, ...fixtures];
|
|
136
|
+
const literal = plan.inventory.filter(route => route.state === 'active' && !route.path.includes('{'));
|
|
137
|
+
assert(4 + cases.length + literal.length * 4 <= MAX_REQUESTS, `Verification would send more than ${MAX_REQUESTS} requests`);
|
|
138
|
+
check(expectRoutes === undefined || plan.inventory.length === expectRoutes, { check: 'probes', severity: 'high', message: 'configured route count differs from --expect-routes', expected: String(expectRoutes), observed: String(plan.inventory.length) });
|
|
139
|
+
|
|
140
|
+
// 1. Probes. A transport failure on the health probe ends the run: nothing
|
|
141
|
+
// else can be said about a deployment that does not answer.
|
|
142
|
+
const health = await send({ path: '/_urlcode/health' });
|
|
143
|
+
if (health.error !== undefined) {
|
|
144
|
+
const tls = destination.protocol === 'https:' && tlsCode.test(health.error);
|
|
145
|
+
check(false, { check: 'transport', severity: 'high', message: tls ? 'TLS certificate rejected by Node\'s default verification' : 'target did not answer the health probe', observed: health.error });
|
|
146
|
+
return finish();
|
|
147
|
+
}
|
|
148
|
+
const parse = (answer ) => { try { const json = JSON.parse(answer.body.toString('utf8')); return isRecord(json) ? json : undefined; } catch { return undefined; } };
|
|
149
|
+
const healthJson = parse(health);
|
|
150
|
+
check(health.status === 200 && healthJson?.status === 'ok' && typeof healthJson.version === 'string' && typeof healthJson.routes === 'number',
|
|
151
|
+
{ check: 'probes', severity: 'high', message: '/_urlcode/health must answer 200 with {status:"ok",version,routes}', expected: '200', observed: `${health.status} ${snippet(health.body)}` });
|
|
152
|
+
const ready = await send({ path: '/_urlcode/ready' }), readyJson = parse(ready);
|
|
153
|
+
check(ready.status === 200 && readyJson?.status === 'ok', { check: 'probes', severity: 'high', message: '/_urlcode/ready must answer 200 (the deployment reports itself degraded or is not URLCode)', expected: '200', observed: `${ready.status} ${snippet(ready.body)}` });
|
|
154
|
+
if (typeof readyJson?.version === 'string') version.observed = readyJson.version;
|
|
155
|
+
if (typeof readyJson?.routes === 'number') routes.observed = readyJson.routes;
|
|
156
|
+
check(version.observed === version.local, { check: 'probes', severity: 'high', message: 'deployed snapshot version differs from the local project (a different deployment or an unpublished change)', expected: version.local, observed: version.observed ?? 'none' });
|
|
157
|
+
check(routes.observed === routes.local, { check: 'probes', severity: 'high', message: 'deployed route count differs from the local project', expected: String(routes.local), observed: routes.observed === null ? 'none' : String(routes.observed) });
|
|
158
|
+
const metrics = await send({ path: '/_urlcode/metrics' });
|
|
159
|
+
if (expectMetrics) check(metrics.status === 200, { check: 'probes', severity: 'medium', message: '/_urlcode/metrics expected but not served', expected: '200', observed: String(metrics.status) });
|
|
160
|
+
else check(metrics.status === 404, { check: 'probes', severity: 'high', message: '/_urlcode/metrics is publicly reachable; keep it internal or pass --expect-metrics', expected: '404', observed: String(metrics.status) });
|
|
161
|
+
|
|
162
|
+
// 2. Fixtures and generated cases, exactly as `urlcode test --target`
|
|
163
|
+
// would send them: sequentially, through hit(), against the target.
|
|
164
|
+
const stub = { address: { address: '127.0.0.1', family: 'IPv4', port: 0 }, root: runtime.root, testPlan: () => plan };
|
|
165
|
+
for (const [i, test] of cases.entries()) {
|
|
166
|
+
requests++;
|
|
167
|
+
const result = await hit(stub, test, agent, destination);
|
|
168
|
+
let route ; try { route = plan.resolve(test.path); } catch { /* an invalid-path negative fixture */ }
|
|
169
|
+
const label = `${i < plan.cases.length ? 'generated' : 'fixture'} case ${i + 1} ${test.method ?? 'GET'} ${test.path}`;
|
|
170
|
+
check(result.pass, { check: 'fixtures', severity: 'high', ...(route === undefined ? {} : { route }), message: result.error ? `${label}: ${result.error} error` : `${label}: response did not match the case`, expected: String(test.status), observed: String(result.status) });
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
// 3. Declared versus observed, per active literal route.
|
|
174
|
+
await each(literal, async route => {
|
|
175
|
+
const config = loaded.routes[route.path] ?? {};
|
|
176
|
+
const effective = effectivePolicies(loaded.document, config);
|
|
177
|
+
const inventory = plan.policies[route.path] ?? {};
|
|
178
|
+
const hasGet = route.methods.includes('GET');
|
|
179
|
+
let path = route.path;
|
|
180
|
+
if (route.path.endsWith('/*')) {
|
|
181
|
+
const file = plan.cases.find(test => test.path.startsWith(route.path.slice(0, -1)) && (test.method ?? 'GET') === 'GET');
|
|
182
|
+
if (!file) return; path = file.path;
|
|
183
|
+
}
|
|
184
|
+
const answer = await send({ path });
|
|
185
|
+
if (answer.error !== undefined) { check(false, { check: 'transport', severity: 'high', route: route.path, message: `GET ${path}: ${answer.error} error` }); return; }
|
|
186
|
+
const { status, headers } = answer;
|
|
187
|
+
if (!hasGet) check(status === 405 && headers.allow === route.methods.join(', '), { check: 'methods', severity: 'medium', route: route.path, message: 'a method the route does not declare must answer 405 with Allow', expected: `405 Allow: ${route.methods.join(', ')}`, observed: `${status} Allow: ${headers.allow ?? 'none'}` });
|
|
188
|
+
else if (config.methods && !route.methods.includes('OPTIONS')) {
|
|
189
|
+
const refused = await send({ path, method: 'OPTIONS' });
|
|
190
|
+
check(refused.status === 405 && refused.headers.allow === route.methods.join(', '), { check: 'methods', severity: 'medium', route: route.path, message: 'OPTIONS on a declared-methods route must answer 405 with Allow', expected: `405 Allow: ${route.methods.join(', ')}`, observed: `${refused.status} Allow: ${refused.headers.allow ?? 'none'}` });
|
|
191
|
+
}
|
|
192
|
+
if (effective.security) for (const [key, value] of expectedSecurity(effective.security, route.path, config, targetOrigin, status)) {
|
|
193
|
+
const hsts = key === 'strict-transport-security';
|
|
194
|
+
check(headers[key] === value, { check: hsts ? 'transport' : 'security', severity: 'high', route: route.path, message: hsts ? 'HSTS missing: the deployment must be started with --origin https://... to emit it' : `security header ${key} differs from the declared profile`, expected: value, observed: headers[key] ?? 'none' });
|
|
195
|
+
}
|
|
196
|
+
const decorated = status < 400 || status === 405;
|
|
197
|
+
const cache = inventory.cache;
|
|
198
|
+
if (cache?.target === 'native' && decorated && route.handler !== 'function' && typeof cache.cacheControl === 'string' && !['explicit response header', 'asset handler'].includes(cache.cacheControl)) {
|
|
199
|
+
check(headers['cache-control'] === cache.cacheControl, { check: 'cache', severity: 'medium', route: route.path, message: `Cache-Control differs from the ${cache.strategy} strategy`, expected: cache.cacheControl, observed: headers['cache-control'] ?? 'none' });
|
|
200
|
+
if (cache.cdnCacheControl) check(headers['cdn-cache-control'] === cache.cdnCacheControl, { check: 'cache', severity: 'medium', route: route.path, message: 'CDN-Cache-Control differs from the declared strategy', expected: cache.cdnCacheControl, observed: headers['cdn-cache-control'] ?? 'none' });
|
|
201
|
+
}
|
|
202
|
+
const throttle = inventory.throttle;
|
|
203
|
+
if (throttle?.target === 'native' && decorated) {
|
|
204
|
+
const expected = throttle.quota !== undefined && throttle.window !== undefined ? `"default";q=${throttle.quota};w=${throttle.window}` : undefined;
|
|
205
|
+
check(expected === undefined ? headers['ratelimit-policy'] !== undefined : headers['ratelimit-policy'] === expected, { check: 'throttle', severity: 'medium', route: route.path, message: 'RateLimit-Policy differs from the declared throttle', expected: expected ?? 'present', observed: headers['ratelimit-policy'] ?? 'none' });
|
|
206
|
+
}
|
|
207
|
+
const compression = inventory.compression;
|
|
208
|
+
if (compression?.target === 'delegated') notes.push(`${route.path}: compression is delegated to the platform on the ${compression.target} target and was not verified`);
|
|
209
|
+
else if (compression?.target === 'native' && status === 200) {
|
|
210
|
+
const types = effective.compression?.types ?? compressibleTypes, minBytes = compression.minBytes ?? effective.compression?.minBytes ?? 1024;
|
|
211
|
+
const secrets = Object.keys(config.secrets ?? {}).length > 0 && effective.compression?.allowWithSecrets !== true;
|
|
212
|
+
const candidate = mediaMatches(types, headers['content-type']) && Number(headers['content-length'] ?? 0) >= minBytes && !/no-transform/i.test(headers['cache-control'] ?? '') && headers['set-cookie'] === undefined && !secrets && !headers['content-encoding'];
|
|
213
|
+
if (candidate) {
|
|
214
|
+
const encodings = compression.encodings ?? effective.compression?.encodings ?? ['br', 'gzip'];
|
|
215
|
+
const encoded = await send({ path, headers: { 'accept-encoding': encodings.join(', ') } });
|
|
216
|
+
check(encodings.some(coding => coding === encoded.headers['content-encoding']), { check: 'compression', severity: 'medium', route: route.path, message: 'a compressible response was served identity despite the declared compression policy', expected: `Content-Encoding in ${encodings.join(', ')}`, observed: encoded.headers['content-encoding'] ?? 'none' });
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
const agents = inventory.agents;
|
|
220
|
+
if (agents?.target === 'native' && agents.mode === 'enforce') {
|
|
221
|
+
const denied = deniedAgent(agents);
|
|
222
|
+
if (denied === undefined) notes.push(`${route.path}: agents policy denies no bundled list, so no denial was verified`);
|
|
223
|
+
else {
|
|
224
|
+
const refused = await send({ path, headers: { 'user-agent': denied } });
|
|
225
|
+
check(refused.status === agents.status, { check: 'agents', severity: 'high', route: route.path, message: 'a User-Agent on the denied bundled list was not refused with the configured status', expected: String(agents.status), observed: String(refused.status) });
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
if (route.generated !== undefined) {
|
|
229
|
+
const type = route.generated === 'site.favicon' ? config.page?.contentType : siteTypes[route.generated];
|
|
230
|
+
check(status === 200 && type !== undefined && (headers['content-type'] ?? '').toLowerCase().startsWith(type), { check: 'site', severity: 'medium', route: route.path, message: `${route.generated} must be served with its content type`, expected: `200 ${type ?? 'unknown'}`, observed: `${status} ${headers['content-type'] ?? 'none'}` });
|
|
231
|
+
if (['site.robots', 'site.securityTxt'].includes(route.generated) && config.respond?.text !== undefined) {
|
|
232
|
+
check(answer.body.toString('utf8') === config.respond.text, { check: 'site', severity: 'medium', route: route.path, message: `${route.generated} body differs from the generated file`, expected: snippet(Buffer.from(config.respond.text)), observed: snippet(answer.body) });
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
if (route.handler === 'respond' && hasGet && status === 200) {
|
|
236
|
+
const head = await send({ path, method: 'HEAD' });
|
|
237
|
+
check(head.status === 200 && head.headers['content-length'] === headers['content-length'] && head.body.length === 0, { check: 'head', severity: 'medium', route: route.path, message: 'HEAD must answer with the Content-Length GET states and no body', expected: `200 Content-Length: ${headers['content-length'] ?? 'none'}`, observed: `${head.status} Content-Length: ${head.headers['content-length'] ?? 'none'}` });
|
|
238
|
+
}
|
|
239
|
+
});
|
|
240
|
+
|
|
241
|
+
// 4. An unmatched path answers 404 with the project-level security
|
|
242
|
+
// headers and the runtime's fixed error headers, which is also how a
|
|
243
|
+
// non-URLCode answerer (a CDN error page, a different app) shows itself.
|
|
244
|
+
const missing = await send({ path: `/_urlcode-verify-${randomBytes(6).toString('hex')}` });
|
|
245
|
+
check(missing.status === 404 && missing.headers['x-content-type-options'] === 'nosniff' && missing.headers['cache-control'] === 'no-store', { check: 'errors', severity: 'high', message: 'an unmatched path must answer the runtime\'s 404 (nosniff, no-store)', expected: '404 nosniff no-store', observed: `${missing.status} ${missing.headers['x-content-type-options'] ?? 'none'} ${missing.headers['cache-control'] ?? 'none'}` });
|
|
246
|
+
for (const [key, value] of errorHeaders(compileErrorPolicy(loaded.document), targetOrigin)) {
|
|
247
|
+
const hsts = key === 'strict-transport-security';
|
|
248
|
+
check(missing.headers[key] === value, { check: hsts ? 'transport' : 'errors', severity: 'high', message: hsts ? 'HSTS missing on error responses: start the deployment with --origin https://...' : `error responses lack the project-level security header ${key}`, expected: value, observed: missing.headers[key] ?? 'none' });
|
|
249
|
+
}
|
|
250
|
+
for (const [pattern, config] of Object.entries(loaded.routes)) {
|
|
251
|
+
if (typeof config.redirect?.url === 'string' && config.redirect.url.startsWith('http:')) check(false, { check: 'transport', severity: 'low', route: pattern, message: 'redirect destination is plain http:', observed: config.redirect.url });
|
|
252
|
+
}
|
|
253
|
+
// 5. Compliance over the declared configuration, with the target as the
|
|
254
|
+
// origin under review unless the operator states another.
|
|
255
|
+
if (compliance) complianceReport = await runCompliance(runtime, { ...compliance, origin: compliance.origin ?? targetOrigin });
|
|
256
|
+
return finish();
|
|
257
|
+
} finally { agent.destroy(); await runtime.close(); }
|
|
258
|
+
|
|
259
|
+
function finish() {
|
|
260
|
+
const order = new Map(severities.map((s, i) => [s, i]));
|
|
261
|
+
findings.sort((a, b) => order.get(a.severity) - order.get(b.severity) || a.check.localeCompare(b.check) || (a.route ?? '').localeCompare(b.route ?? ''));
|
|
262
|
+
const counts = { high: 0, medium: 0, low: 0, info: 0 };
|
|
263
|
+
for (const finding of findings) counts[finding.severity]++;
|
|
264
|
+
// Severity order counts down from high = 0, so "at or above" is index <= threshold and none is -1.
|
|
265
|
+
const threshold = failOn === 'none' ? -1 : order.get(failOn) ;
|
|
266
|
+
const failing = findings.some(finding => order.get(finding.severity) <= threshold);
|
|
267
|
+
const pass = !failing && (complianceReport === null || complianceReport.pass || complianceWarn);
|
|
268
|
+
return { target: targetOrigin, version, routes, requests, checks, findings, counts, notes, failOn, pass, compliance: complianceReport };
|
|
269
|
+
}
|
|
270
|
+
}
|
package/docs/AI-AUTHORING.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Building URLCode projects with an AI assistant
|
|
2
2
|
|
|
3
|
-
Use this as project-authoring context. It describes the implemented 0.
|
|
3
|
+
Use this as project-authoring context. It describes the implemented source contract, including unreleased additions after 0.3.0,
|
|
4
4
|
not a general server framework. Runtime/schema/docs
|
|
5
5
|
must come from the same reviewed revision. The runtime is Apache-2.0; a
|
|
6
6
|
project you generate carries whatever license its owner chooses, so do not
|
|
@@ -14,19 +14,44 @@ add one to it automatically.
|
|
|
14
14
|
4. [Routing](ROUTING.md), [HTTP](HTTP.md), [middleware](MIDDLEWARE.md), [assets](ASSETS.md).
|
|
15
15
|
5. [Sandbox and operator grants](FUNCTION-SECURITY.md).
|
|
16
16
|
6. [Readiness](READINESS.md), [capacity](CAPACITY.md), [DDoS/recovery](RESILIENCE.md).
|
|
17
|
+
7. [The framework](FRAMEWORK.md) for accounts, administration and presentation:
|
|
18
|
+
`extensions.<name>` blocks and `extension` mounts are the only YAML those
|
|
19
|
+
packages need; their configuration is documented in their own repositories.
|
|
17
20
|
|
|
18
|
-
The root [llms.txt](../llms.txt) is a compact discovery index
|
|
21
|
+
The root [llms.txt](../llms.txt) is a compact discovery index; the generated
|
|
22
|
+
[llms-full.txt](../llms-full.txt) concatenates the authoring documents above in
|
|
23
|
+
reading order for agents that want complete context in one fetch. It is a convenience,
|
|
19
24
|
not a runtime protocol or a guarantee that AI clients automatically consume it.
|
|
20
25
|
The generated reference is checked against the schema in `npm run verify`.
|
|
21
26
|
|
|
22
27
|
Follow [organization and readability practices](BEST-PRACTICES.md): preserve local
|
|
23
28
|
conventions, use clear names, keep middleware focused and avoid needless layers.
|
|
24
29
|
|
|
30
|
+
## Generated project guide and agent skill
|
|
31
|
+
|
|
32
|
+
A project created with `urlcode init` contains an `AGENTS.md` generated from the
|
|
33
|
+
installed runtime's capability catalog: it names the native handlers, policies
|
|
34
|
+
and site keys of that version, the sandbox limits, the three commands that count
|
|
35
|
+
as evidence, and the rules on grants and secrets. Assistants that load skills
|
|
36
|
+
find the same loop in `skills/urlcode/SKILL.md` inside the installed package; it
|
|
37
|
+
teaches how to retrieve the minimum reference through `urlcode capabilities`,
|
|
38
|
+
`urlcode recipes list|show` and `urlcode validate --local` rather than reading
|
|
39
|
+
the documentation whole. Neither file replaces the schema; both defer to it.
|
|
40
|
+
|
|
25
41
|
## Authoring workflow
|
|
26
42
|
|
|
43
|
+
Run `urlcode context --project ./my-links` first. It prints, in a few hundred
|
|
44
|
+
tokens, the runtime and schema version, what the project already uses, the
|
|
45
|
+
constraints that hold for every project, which targets refuse this project's
|
|
46
|
+
features and the exact validate, test and audit commands with the intentional
|
|
47
|
+
route count filled in. It is derived from the compiled project and the
|
|
48
|
+
capability catalog, never from prose, so prefer it to re-reading the
|
|
49
|
+
documentation; add `--budget N` when context is scarce and `--json` for
|
|
50
|
+
tooling. The same data is available from the MCP tool `get_context`.
|
|
51
|
+
|
|
27
52
|
- Inspect the existing entry point, included files, functions, tests and pinned
|
|
28
53
|
runtime. Preserve the user's organization and unrelated routes.
|
|
29
|
-
- Choose exactly one handler: function, redirect, respond, page, static, download, link.
|
|
54
|
+
- Choose exactly one handler: function, redirect, respond, page, static, download, link, proxy, or conditional.
|
|
30
55
|
Add optional middleware around it. Prefer native handlers when code is unnecessary.
|
|
31
56
|
- Declare each path placeholder as a required string. Paths use whole segments;
|
|
32
57
|
no regex, greedy captures or general-purpose wildcard functions.
|
|
@@ -62,14 +87,15 @@ The benchmark operates locally; it is not a load test of an external deployment.
|
|
|
62
87
|
|---|---|
|
|
63
88
|
| Strict YAML v1 contract + JSON Schema | YAML anchors/aliases, template interpolation, remote includes |
|
|
64
89
|
| Explicit included files | Recursive includes or glob discovery |
|
|
65
|
-
| Exact and
|
|
66
|
-
|
|
|
90
|
+
| Exact/parameter paths and bounded exact request conditions | Regex, greedy/optional segments, arbitrary client-Host routing |
|
|
91
|
+
| Native handlers, explicit conditional redirect/respond cases and ordered route middleware | Global middleware, Express compatibility, automatic auth |
|
|
92
|
+
| `function: functions/x.mjs` and `middleware: [middleware/y.mjs]` short forms expanding to the long form (path `{param}`s become required strings, maxLength 128, and `args`) | Short forms for query/header/env/secret arguments or named exports; write those long |
|
|
67
93
|
| Text/JSON Request/Response sandbox | fetch, Node/npm APIs, filesystem, WebSocket, streaming, crypto API |
|
|
68
|
-
| Named bindings and external
|
|
69
|
-
| Native
|
|
94
|
+
| Named bindings and external revision-pinned binding/egress grants | Automatic provider secret stores, self-granted permissions |
|
|
95
|
+
| Native assets/downloads and operator-granted bounded HTTPS proxy | Content sniffing, large-file streaming, arbitrary guest network access |
|
|
70
96
|
| Parameter validation and JSON body syntax checks | Full OpenAPI or JSON Schema validation of request bodies |
|
|
71
97
|
| Local test/audit/benchmark | Route-local YAML tests, managed monitoring, production load certification |
|
|
72
|
-
| Local
|
|
98
|
+
| Local/self-hosted runtime; limited AWS/Vercel/Cloudflare implementations with local tests | Verified provider deployments or full cross-provider parity |
|
|
73
99
|
| File authoring, snapshot reload, native stored links and separate authenticated management API | General guest storage broker, distributed link-store adapter |
|
|
74
100
|
| Optional host `policies` (`throttle`, `agents`, `security`, `compression`, `cache`) and reusable `profiles` | Plugins named in YAML, shared multi-instance counters, CORS, verified-bot checks |
|
|
75
101
|
| Optional top-level `site` (`robots`, `sitemap`, `favicon`, `securityTxt`, `llms`) generating native routes | Per-route `noindex` field, sitemap index files, `humans.txt`, signed `security.txt` |
|
|
@@ -83,12 +109,105 @@ per-target table in [policies](POLICIES.md) before declaring `throttle`,
|
|
|
83
109
|
`compression` or `cache` for a serverless or Cloudflare deployment, because an
|
|
84
110
|
unsupported policy refuses activation rather than degrading.
|
|
85
111
|
|
|
112
|
+
When the project declares `extensions.auth` (an operator-installed extension,
|
|
113
|
+
see [extensions](EXTENSIONS.md)), protect a route with the short form
|
|
114
|
+
`auth: true` or `auth: {role: member}` rather than writing
|
|
115
|
+
`policies.extensions.auth` by hand; the compiler expands it to that long form
|
|
116
|
+
and `routes`/`audit` show the expansion. Do not use both forms on one route,
|
|
117
|
+
and do not declare `auth` in a project without `extensions.auth`; both refuse
|
|
118
|
+
to load. Only `required`, `role`, `permission`, `verified`,
|
|
119
|
+
`freshWithinSeconds` and `onDeny` are accepted; there is no `roles` or
|
|
120
|
+
`permissions` list. `auth: {required: false}` emits nothing.
|
|
121
|
+
|
|
86
122
|
`site` is valid YAML in this contract (entry file only, every key off unless
|
|
87
123
|
declared). Prefer it over hand-written `robots.txt`/`security.txt` routes; a
|
|
88
124
|
declared route at the same path still wins. Count its generated routes in
|
|
89
125
|
`--expect-routes`. `site.sitemap` needs `--origin` at every command that
|
|
90
126
|
activates the project; see [site conventions](SITE.md).
|
|
91
127
|
|
|
128
|
+
## Agent skills
|
|
129
|
+
|
|
130
|
+
This repository ships two agent skills, each a thin trigger pointing at the
|
|
131
|
+
docs that are the actual source of truth, so there is one place to keep
|
|
132
|
+
current rather than two:
|
|
133
|
+
|
|
134
|
+
- [`urlcode-authoring`](../.claude/skills/urlcode-authoring/SKILL.md) — this
|
|
135
|
+
guide, the schema and the reference. It loads the capability limits and the
|
|
136
|
+
validate/test/audit loop before YAML is written.
|
|
137
|
+
- [`urlcode-operations`](../.claude/skills/urlcode-operations/SKILL.md) —
|
|
138
|
+
deployment, `verify-deployment`, capacity, resilience, monitoring and the
|
|
139
|
+
private management API. Authoring and operating are deliberately separate
|
|
140
|
+
skills so neither triggers on the other's task.
|
|
141
|
+
|
|
142
|
+
Both do what `llms.txt` cannot: `llms.txt` is a passive index an assistant may
|
|
143
|
+
never read, while a triggered skill loads automatically for a matching task.
|
|
144
|
+
|
|
145
|
+
Three ways to get either, all pinned to a runtime revision:
|
|
146
|
+
|
|
147
|
+
- **Clone or template.** A clone of this repository, or a project created from
|
|
148
|
+
[urlcode-template](https://github.com/jimhoyd-com/urlcode-template), carries
|
|
149
|
+
`.claude/skills/` at the project root and loads it with no further setup.
|
|
150
|
+
- **npm.** The published package includes both skill directories. Copy the
|
|
151
|
+
one(s) you want into your project's `.claude/skills/` to pin guidance to the
|
|
152
|
+
same revision as the runtime you installed; a skill inside `node_modules` is
|
|
153
|
+
not discovered on its own.
|
|
154
|
+
- **Plugin marketplace.** `.claude-plugin/marketplace.json` publishes the
|
|
155
|
+
`packaging/claude-plugin` distribution from this repository, carrying both
|
|
156
|
+
skills. Add the marketplace by its Git URL and install the `urlcode` plugin.
|
|
157
|
+
This copy tracks the branch you install from rather than your installed
|
|
158
|
+
runtime, so prefer one of the first two when the project pins an older
|
|
159
|
+
release.
|
|
160
|
+
|
|
161
|
+
`npm run docs:plugin` regenerates the plugin distribution from both skills;
|
|
162
|
+
`npm run check` fails if it is stale or if either skill names a documentation
|
|
163
|
+
path this revision does not ship.
|
|
164
|
+
## Bounded authoring tools
|
|
165
|
+
|
|
166
|
+
Before generating a common route by hand, search the bundled catalog:
|
|
167
|
+
`urlcode recipes search "<what the route does>"` (MCP `search_recipes`) matches
|
|
168
|
+
id, description, tags and capabilities locally, and `recipes show NAME` prints
|
|
169
|
+
the metadata first: capabilities, per-target verdicts derived from the
|
|
170
|
+
capability preflight, required services and operator grants, inputs to edit,
|
|
171
|
+
the exact validate/test/audit commands and expected behavior. `urlcode examples
|
|
172
|
+
search <text>` (MCP `search_examples`) answers the smallest runnable example and,
|
|
173
|
+
for the cookbook, the single route that demonstrates it. `recipes add NAME --out
|
|
174
|
+
NEW_DIRECTORY` creates a standalone project; it never merges existing routes. `bulk-import csv INPUT --out NEW_DIRECTORY`
|
|
175
|
+
converts strict redirect rows into deterministic 1,000-route include files with
|
|
176
|
+
source fingerprints. Both support `--dry-run`. See [recipes](RECIPES.md),
|
|
177
|
+
[bulk import and measured limits](BULK.md), and [interchange](INTERCHANGE.md).
|
|
178
|
+
Provider conversion requires explicit acknowledgment of semantic differences;
|
|
179
|
+
do not describe an acknowledged migration candidate as lossless.
|
|
180
|
+
|
|
181
|
+
Guest TypeScript needs `build-typescript --project SOURCE --out NEW_DIRECTORY`
|
|
182
|
+
before serving. Only the emitted `.js`/`.mjs` executes in QuickJS. The build
|
|
183
|
+
transpiles rather than type-checks and ignores project compiler configuration,
|
|
184
|
+
plugins, package scripts and dotenv files. Apply operator grants to the built
|
|
185
|
+
revision. See [TypeScript authoring](TYPESCRIPT-AUTHORING.md).
|
|
186
|
+
|
|
187
|
+
Use [conditions](CONDITIONS.md) for exact query/header/cookie/host/method
|
|
188
|
+
predicates. Cases must be provably disjoint, remain no-store and use only
|
|
189
|
+
redirect/respond branches. Conditions are not authentication or grants.
|
|
190
|
+
Cloudflare refuses conditions in this implementation.
|
|
191
|
+
|
|
192
|
+
Use [proxy and signals](EGRESS.md) only with explicitly reviewed external
|
|
193
|
+
origin grants pinned to the project revision. These are self-hosted features;
|
|
194
|
+
providers refuse them. Signals are bounded best effort with drops, no retries
|
|
195
|
+
or persistence. Never turn a user request into an implicit network grant.
|
|
196
|
+
|
|
197
|
+
Before using a feature, ask `urlcode capabilities <name>` for its constraints, grants and target support and `urlcode schema <path>` for only that YAML fragment (MCP: `get_capability`, `get_schema`), instead of guessing.
|
|
198
|
+
The [tooling SDK and stdio MCP](TOOLING.md) inspect, validate, explain and preview
|
|
199
|
+
without guest execution, environment reads or writes. Run `urlcode explain /route`
|
|
200
|
+
to check effective methods, policies and cache outcome, and `urlcode manifest`
|
|
201
|
+
for the generated route, capability and requirement summary, instead of
|
|
202
|
+
inferring either from the YAML. MCP roots are selected by
|
|
203
|
+
the operator, never by tool arguments; `--allow-authoring` on the operator's
|
|
204
|
+
command line adds project-confined route, recipe, scaffold and runner tools.
|
|
205
|
+
`urlcode init` writes `.mcp.json` so Claude Code and Codex register the read-only
|
|
206
|
+
server for the project ([registering the server](TOOLING.md#registering-the-server)).
|
|
207
|
+
Inspection is not activation/deployment readiness: real grants, asset snapshots
|
|
208
|
+
and service availability still need normal runtime checks. Provider conformance replay is local evidence; only
|
|
209
|
+
explicit live [deployment observations](PROVIDER-VERIFICATION.md) test ingress.
|
|
210
|
+
|
|
92
211
|
## Copyable task prompt
|
|
93
212
|
|
|
94
213
|
> Build the requested routes for URLCode using the pinned runtime's JSON Schema,
|
|
@@ -111,3 +230,6 @@ integrations should be identified as gaps, not silently bypass the sandbox.
|
|
|
111
230
|
For live `link` handlers, set `dynamicLinks: true` only in the entry urlcode.yaml.
|
|
112
231
|
It defaults to false. Do not add this flag to includes or enable it merely for
|
|
113
232
|
parameterized redirects/functions. Store bindings are still operator-owned.
|
|
233
|
+
|
|
234
|
+
See [capabilities and normalized route representation](CAPABILITIES.md) for the target catalog,
|
|
235
|
+
programmatic compatibility analysis and provider verification limits.
|