@getnote/mcp 1.10.0 → 1.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +22 -3
- package/dist/admission.d.ts +16 -0
- package/dist/admission.d.ts.map +1 -0
- package/dist/admission.js +95 -0
- package/dist/client.d.ts +28 -4
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +212 -39
- package/dist/index.js +36 -11
- package/dist/read-retry.d.ts +3 -1
- package/dist/read-retry.d.ts.map +1 -1
- package/dist/read-retry.js +42 -3
- package/dist/upload-operation.d.ts +24 -0
- package/dist/upload-operation.d.ts.map +1 -0
- package/dist/upload-operation.js +18 -0
- package/package.json +1 -1
- package/src/admission.ts +67 -0
- package/src/client.ts +177 -41
- package/src/index.ts +38 -11
- package/src/read-retry.ts +32 -4
- package/src/upload-operation.ts +20 -0
- package/test/admission-v2.test.mjs +67 -0
- package/test/upload-http-boundary.test.mjs +47 -0
- package/test/upload-recovery.test.mjs +53 -0
- package/test/upload-safety.test.mjs +133 -0
- package/test/upload-v2-protocol.test.mjs +30 -0
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
import http from 'node:http';
|
|
3
|
+
import test from 'node:test';
|
|
4
|
+
import {GetNoteClient,GetNoteAPIError} from '../dist/client.js';
|
|
5
|
+
|
|
6
|
+
const refusal={dimension:'qps',bucket:'global',request_execution:'not_started',retry_action:'retry_same_operation',retryable:true,retry_after_ms:1,future:{version:3}};
|
|
7
|
+
async function fixture(t,handler){const server=http.createServer(handler);await new Promise(r=>server.listen(0,'127.0.0.1',r));t.after(async()=>{server.closeAllConnections();await new Promise(r=>server.close(r))});return `http://127.0.0.1:${server.address().port}`;}
|
|
8
|
+
function fail(res,detail=refusal){res.writeHead(429,{'content-type':'application/json'});res.end(JSON.stringify({success:false,error:{code:10202,reason:'qps_exceeded',message:'wait',retryable:true,rate_limit_detail:detail},request_id:'v2-request'}));}
|
|
9
|
+
function ok(res,data={id:'1'}){res.setHeader('content-type','application/json');res.end(JSON.stringify({success:true,data}));}
|
|
10
|
+
|
|
11
|
+
test('v2 refusal retries identical note body including uploaded URLs and note key',async t=>{
|
|
12
|
+
const bodies=[];const base=await fixture(t,(req,res)=>{let body='';req.on('data',c=>body+=c);req.on('end',()=>{bodies.push(body);if(bodies.length===1)fail(res);else ok(res)})});
|
|
13
|
+
const client=new GetNoteClient('key','client',base);await client.saveNote({content:'photo',note_type:'img_text',image_urls:['https://oss.test/original'],client_request_id:'note-original'});
|
|
14
|
+
assert.equal(bodies.length,2);assert.equal(bodies[0],bodies[1]);assert.equal(JSON.parse(bodies[1]).client_request_id,'note-original');
|
|
15
|
+
});
|
|
16
|
+
test('v2 full detail survives refusal without replay for unsafe execution and malformed detail',async t=>{
|
|
17
|
+
for(const detail of [{...refusal,request_execution:'admitted'},{...refusal,request_execution:'unknown'},{...refusal,dimension:'day'},null,{...refusal,retryable:'true'}]){
|
|
18
|
+
let calls=0;const base=await fixture(t,(req,res)=>{calls++;fail(res,detail)});await assert.rejects(()=>new GetNoteClient('key','client',base).getNote('1'),e=>{assert(e instanceof GetNoteAPIError);assert.deepEqual(e.rateLimitDetail,detail);assert.equal(e.requestId,'v2-request');return true});assert.equal(calls,1);
|
|
19
|
+
}
|
|
20
|
+
});
|
|
21
|
+
test('same process identity serializes across retries; a separate authorization is independent',async t=>{
|
|
22
|
+
const order=[];let first=true;const base=await fixture(t,(req,res)=>{const id=new URL(req.url,'http://local').searchParams.get('id');order.push(id);if(id==='1'&&first){first=false;fail(res,{...refusal,retry_after_ms:120})}else ok(res)});
|
|
23
|
+
const one=new GetNoteClient('key','client',base);const two=new GetNoteClient('key','client',base+'/open');const other=new GetNoteClient('other','client',base);
|
|
24
|
+
const firstCall=one.getNote('1');await new Promise(r=>setTimeout(r,25));await Promise.all([firstCall,two.withSignal(new AbortController().signal).getNote('2'),other.getNote('3')]);assert.deepEqual(order,['1','3','1','2']);
|
|
25
|
+
});
|
|
26
|
+
test('queue cancellation stops a queued identity call before HTTP dispatch',async t=>{
|
|
27
|
+
const ids=[];let release;const held=new Promise(r=>release=r);const base=await fixture(t,async(req,res)=>{ids.push(new URL(req.url,'http://local').searchParams.get('id'));if(ids.length===1)await held;ok(res)});
|
|
28
|
+
const c=new GetNoteClient('key','client',base);const first=c.getNote('1');await new Promise(r=>setTimeout(r,25));const abort=new AbortController();const queued=c.withSignal(abort.signal).getNote('2');abort.abort(new Error('stop queued'));await assert.rejects(queued,/stop queued/);release();await first;assert.deepEqual(ids,['1']);
|
|
29
|
+
});
|
|
30
|
+
test('learned quota policy paces subsequent requests using effective global rate',async t=>{
|
|
31
|
+
const times=[];const base=await fixture(t,(req,res)=>{times.push(Date.now());ok(res,req.url.includes('/quota')?{rate_limit_policy:{version:'custom',rates:{global:{sustained_rate_per_second:20}}}}:{id:'1'})});
|
|
32
|
+
const c=new GetNoteClient('key','client',base);await c.getQuota();await Promise.all([c.getNote('1'),new GetNoteClient('key','client',base).getNote('2')]);assert.ok(times[2]-times[1]>=40,`${times}`);
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
test('retry pacing cannot extend the bounded wait budget and keeps original advice',async t=>{
|
|
36
|
+
let calls=0;const base=await fixture(t,(req,res)=>{calls++;fail(res,{...refusal,sustained_rate_per_second:0.01})});
|
|
37
|
+
const abort=new AbortController();const timer=setTimeout(()=>abort.abort(new Error('test deadline')),300);const start=Date.now();
|
|
38
|
+
try{await assert.rejects(()=>new GetNoteClient('key','client',base).withSignal(abort.signal).saveNote({content:'once'}),e=>e instanceof GetNoteAPIError&&e.requestId==='v2-request');assert.ok(Date.now()-start<200);assert.equal(calls,1)}finally{clearTimeout(timer);abort.abort()}
|
|
39
|
+
});
|
|
40
|
+
test('safe retry snapshots the original body before caller data can mutate',async t=>{
|
|
41
|
+
const bodies=[];const body={content:'original',image_urls:['https://oss.test/original'],client_request_id:'same-key'};
|
|
42
|
+
const base=await fixture(t,(req,res)=>{let raw='';req.on('data',chunk=>raw+=chunk);req.on('end',()=>{bodies.push(raw);if(bodies.length===1){body.content='mutated';body.image_urls.push('https://oss.test/unrelated');fail(res)}else ok(res)})});
|
|
43
|
+
await new GetNoteClient('key','client',base).saveNote(body);assert.deepEqual(bodies.map(JSON.parse),[{content:'original',image_urls:['https://oss.test/original'],client_request_id:'same-key'},{content:'original',image_urls:['https://oss.test/original'],client_request_id:'same-key'}]);
|
|
44
|
+
});
|
|
45
|
+
test('QPS error advice paces the next queued request even if the refused operation cannot retry',async t=>{
|
|
46
|
+
const times=[];const base=await fixture(t,(req,res)=>{times.push(Date.now());if(times.length===1)fail(res,{...refusal,request_execution:'admitted',sustained_rate_per_second:20});else ok(res)});
|
|
47
|
+
const c=new GetNoteClient('key','client',base);await assert.rejects(()=>c.saveNote({content:'refused'}));await c.getNote('1');assert.ok(times[1]-times[0]>=40);
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
test('idle identity entries expire with advisory pacing instead of retaining authorization state forever',async t=>{
|
|
51
|
+
const {inAuthorizationQueue,learnPolicy,pace}=await import('../dist/admission.js');
|
|
52
|
+
t.mock.timers.enable({apis:['setTimeout']});
|
|
53
|
+
await inAuthorizationQueue('idle-test-only',undefined,async queue=>{learnPolicy(queue,{rate_limit_policy:{rates:{global:{sustained_rate_per_second:0.01}}}});assert.equal(await pace(queue,'read'),true)});
|
|
54
|
+
t.mock.timers.tick(300001);
|
|
55
|
+
const admitted=await inAuthorizationQueue('idle-test-only',undefined,queue=>pace(queue,'read',undefined,0));
|
|
56
|
+
assert.equal(admitted,true,'the expired identity must not retain its old pacing state');
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
test('v2 refuses malformed outer retryability, malformed wait and unknown operations',async t=>{
|
|
60
|
+
const {readRetryDelay}=await import('../dist/read-retry.js');
|
|
61
|
+
const error={httpStatus:429,code:10202,reason:'qps_exceeded',retryable:true,rateLimitDetail:refusal};
|
|
62
|
+
assert.equal(readRetryDelay('POST','/resource/note/save',{...error,retryable:'true'},0,0),undefined);
|
|
63
|
+
assert.equal(readRetryDelay('POST','/resource/note/save',{...error,rateLimitDetail:{...refusal,retry_after_ms:'1'}},0,0),undefined);
|
|
64
|
+
assert.equal(readRetryDelay('GET','/resource/new-upload',error,0,0),undefined);
|
|
65
|
+
assert.equal(readRetryDelay('POST','/resource/unknown-write',error,0,0),undefined);
|
|
66
|
+
assert.equal(readRetryDelay('GET','/resource/image/upload_token',error,0,0),undefined);
|
|
67
|
+
});
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
import http from 'node:http';
|
|
3
|
+
import test from 'node:test';
|
|
4
|
+
import {GetNoteClient} from '../dist/client.js';
|
|
5
|
+
|
|
6
|
+
function ok(res,data){res.setHeader('content-type','application/json');res.end(JSON.stringify({success:true,data}));}
|
|
7
|
+
async function fixture(t,handler){const server=http.createServer(handler);await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve));t.after(async()=>{server.closeAllConnections();await new Promise(resolve=>server.close(resolve))});return `http://127.0.0.1:${server.address().port}`;}
|
|
8
|
+
|
|
9
|
+
test('legacy missing configuration preserves one-shot issuance for plain and non-envelope HTTP errors',async t=>{
|
|
10
|
+
for(const kind of ['image','file'])for(const format of ['plain','json','empty'])for(const status of (kind==='file'?[404,403]:[404]))await t.test(`${kind} ${status} ${format}`,async t=>{
|
|
11
|
+
let issued=0;
|
|
12
|
+
const base=await fixture(t,(req,res)=>{
|
|
13
|
+
if(req.url.includes('/config')||req.url.includes('/capabilities')){res.writeHead(status,{'content-type':format==='json'?'application/json':'text/plain'});res.end(format==='json'?'{}':format==='plain'?'404 page not found':'');return}
|
|
14
|
+
issued++;assert.equal(req.headers['idempotency-key'],undefined);ok(res,{object_key:'legacy-original'});
|
|
15
|
+
});
|
|
16
|
+
const client=new GetNoteClient('key','client',base);
|
|
17
|
+
const result=kind==='image'?await client.getUploadToken({mime_type:'png'}):await client.getKnowledgeFileUploadToken('pdf');assert.equal(result.object_key,'legacy-original');
|
|
18
|
+
await assert.rejects(()=>kind==='image'?client.getUploadToken({mime_type:'png',operation_id:'original'}):client.getKnowledgeFileUploadToken('pdf','original'),error=>error.reason==='upload_operation_unsupported');assert.equal(issued,1);
|
|
19
|
+
});
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
test('plain unavailable configuration cannot authorize blind issuance',async t=>{
|
|
23
|
+
let issued=0;const base=await fixture(t,(req,res)=>{if(req.url.includes('/capabilities')){res.writeHead(503);res.end('unavailable');return}issued++;ok(res,{})});
|
|
24
|
+
await assert.rejects(()=>new GetNoteClient('key','client',base).getKnowledgeFileUploadToken('pdf'));assert.equal(issued,0);
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
test('cancelling an in-flight OSS upload stops the transfer and retains its original operation',async t=>{
|
|
28
|
+
let announce;const received=new Promise(resolve=>announce=resolve);let issues=0,uploads=0;
|
|
29
|
+
const base=await fixture(t,(req,res)=>{
|
|
30
|
+
if(req.url.includes('/config'))return ok(res,{runtime:{governance_enabled:true,operation_replay:true,idempotency_header:'Idempotency-Key',operation_status_endpoint:'/open/api/v1/resource/image/upload_operation'}});
|
|
31
|
+
if(req.url.includes('/upload_token')){issues++;return ok(res,{operation_id:'original',resume_until:'2099-01-01T00:00:00Z',host:base+'/oss',object_key:'original-object',accessid:'fixture',policy:'fixture',signature:'fixture',callback:'fixture',oss_content_type:'image/png',access_url:'https://example.test/original'})}
|
|
32
|
+
if(req.url==='/oss'){uploads++;req.on('data',()=>{});announce();return}
|
|
33
|
+
throw new Error('Unexpected test route');
|
|
34
|
+
});
|
|
35
|
+
const abort=new AbortController();let settled=false;
|
|
36
|
+
const pending=new GetNoteClient('key','client',base).withSignal(abort.signal).uploadImage(Buffer.from('fixture'),'png','original').then(()=>{settled=true;throw new Error('cancelled upload succeeded')},error=>{settled=true;assert.equal(error.operationId,'original');assert.equal(error.reason,'upload_result_unconfirmed')});
|
|
37
|
+
await received;abort.abort(new Error('cancel upload'));
|
|
38
|
+
await Promise.race([pending,new Promise((_,reject)=>setTimeout(()=>reject(new Error('cancelled OSS request remained active')),250))]);
|
|
39
|
+
assert.equal(settled,true);assert.equal(issues,1);assert.equal(uploads,1);
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
test('OSS redirects never repost the same uploaded object',async t=>{
|
|
43
|
+
let redirected=0;
|
|
44
|
+
const base=await fixture(t,(req,res)=>{if(req.url==='/oss'){res.writeHead(307,{location:base+'/again'});res.end();return}redirected++;res.setHeader('content-type','application/json');res.end('{"h":{"c":0},"c":{"image":{"id":"unexpected"}}}')});
|
|
45
|
+
await assert.rejects(()=>new GetNoteClient('key','client',base).uploadImageToOSS({host:base+'/oss',object_key:'original',accessid:'fixture',policy:'fixture',signature:'fixture',callback:'fixture',oss_content_type:'image/png'},Buffer.from('fixture')));
|
|
46
|
+
assert.equal(redirected,0);
|
|
47
|
+
});
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
import http from 'node:http';
|
|
3
|
+
import test from 'node:test';
|
|
4
|
+
import {GetNoteClient,GetNoteAPIError} from '../dist/client.js';
|
|
5
|
+
|
|
6
|
+
const routes={image:'/resource/image',file:'/resource/knowledge/file'};
|
|
7
|
+
function runtime(kind){return {governance_enabled:true,operation_replay:true,idempotency_header:'Idempotency-Key',operation_status_endpoint:'/open/api/v1'+routes[kind]+'/upload_operation'};}
|
|
8
|
+
function ok(res,data){res.setHeader('content-type','application/json');res.end(JSON.stringify({success:true,data}));}
|
|
9
|
+
function fail(res,reason,code=40901,status=409){res.writeHead(status,{'content-type':'application/json'});res.end(JSON.stringify({success:false,error:{code,reason,message:reason,retryable:false},request_id:'req-operation'}));}
|
|
10
|
+
async function fixture(t,handler){const server=http.createServer(handler);await new Promise(r=>server.listen(0,'127.0.0.1',r));t.after(async()=>{server.closeAllConnections();await new Promise(r=>server.close(r))});return `http://127.0.0.1:${server.address().port}`;}
|
|
11
|
+
function issue(client,kind,id){return kind==='image'?client.getUploadToken({mime_type:'png',operation_id:id}):client.getKnowledgeFileUploadToken('pdf',id);}
|
|
12
|
+
function token(){return {resume_until:'2099-01-01T00:00:00Z',signature:'SENSITIVE_SIGNATURE',access_url:'https://oss.test/original'};}
|
|
13
|
+
|
|
14
|
+
test('lost credential response recovers exactly the original operation without minting again',async t=>{
|
|
15
|
+
for(const kind of ['image','file'])await t.test(kind,async t=>{
|
|
16
|
+
let minted=0;let key;const queries=[];
|
|
17
|
+
const base=await fixture(t,(req,res)=>{const url=new URL(req.url,'http://local');if(url.pathname.endsWith('/config')||url.pathname.endsWith('/capabilities'))return ok(res,{runtime:runtime(kind)});if(url.pathname.endsWith('/upload_token')){minted++;key=req.headers['idempotency-key'];req.socket.destroy();return}queries.push(url.searchParams.get('operation_id'));ok(res,{operation_id:key,state:'issued',resume_until:'2099-01-01T00:00:00Z',credential:token()})});
|
|
18
|
+
const result=await issue(new GetNoteClient('key','client',base),kind,undefined);assert.equal(result.access_url,'https://oss.test/original');assert.match(key,/^[A-Za-z0-9._:-]{1,128}$/);assert.equal(result.operation_id,key);assert.equal(minted,1);assert.deepEqual(queries,[key]);
|
|
19
|
+
});
|
|
20
|
+
});
|
|
21
|
+
test('negotiated credential QPS retry reuses the exact header and query',async t=>{
|
|
22
|
+
const calls=[];const base=await fixture(t,(req,res)=>{if(req.url.includes('/config'))return ok(res,{runtime:runtime('image')});calls.push({url:req.url,key:req.headers['idempotency-key']});if(calls.length===1){res.writeHead(429,{'content-type':'application/json'});res.end(JSON.stringify({success:false,error:{code:10202,reason:'qps_exceeded',message:'wait',retryable:true,rate_limit_detail:{dimension:'qps',request_execution:'not_started',retry_action:'retry_same_operation',retryable:true,retry_after_ms:1}}}));return}ok(res,token())});
|
|
23
|
+
await issue(new GetNoteClient('key','client',base),'image','original:key');assert.deepEqual(calls,[{url:'/open/api/v1/resource/image/upload_token?mime_type=png',key:'original:key'},{url:'/open/api/v1/resource/image/upload_token?mime_type=png',key:'original:key'}]);
|
|
24
|
+
});
|
|
25
|
+
test('legacy and disabled runtime omit idempotency header; explicit recovery fails before mint',async t=>{
|
|
26
|
+
for(const rt of [undefined,{...runtime('image'),governance_enabled:false},{...runtime('image'),operation_replay:false},{...runtime('image'),idempotency_header:'Other-Key'}]){
|
|
27
|
+
const minted=[];const base=await fixture(t,(req,res)=>{if(req.url.includes('/config'))return ok(res,{runtime:rt});minted.push(req.headers['idempotency-key']);ok(res,token())});const c=new GetNoteClient('key','client',base);await issue(c,'image');assert.deepEqual(minted,[undefined]);await assert.rejects(()=>issue(c,'image','explicit-key'),e=>e.reason==='upload_operation_unsupported'&&e.retryable===false);assert.equal(minted.length,1);
|
|
28
|
+
}
|
|
29
|
+
});
|
|
30
|
+
test('invalid operation identifiers never reach configuration or issuance',async t=>{
|
|
31
|
+
let requests=0;const base=await fixture(t,(req,res)=>{requests++;ok(res,{})});for(const id of ['', 'bad key','a'.repeat(129)])await assert.rejects(()=>issue(new GetNoteClient('key','client',base),'image',id),/operation_id/);assert.equal(requests,0);
|
|
32
|
+
});
|
|
33
|
+
test('unconfirmed, unavailable, expiry and unknown lookup keep original key and do not remint',async t=>{
|
|
34
|
+
for(const [issueReason,statusState]of [['credential_operation_unconfirmed','processing'],['credential_operation_unavailable','needs_reconciliation'],['credential_operation_unconfirmed','expired'],['credential_operation_unavailable','not_found']]){
|
|
35
|
+
let minted=0,lookups=0;const base=await fixture(t,(req,res)=>{if(req.url.includes('/capabilities'))return ok(res,{runtime:runtime('file')});if(req.url.includes('/upload_token')){minted++;return fail(res,issueReason)}lookups++;if(statusState==='not_found')return fail(res,'credential_operation_not_found',40401,404);ok(res,{operation_id:'keep-me',state:statusState,resume_until:'2099-01-01T00:00:00Z',credential:token()})});
|
|
36
|
+
await assert.rejects(()=>issue(new GetNoteClient('key','client',base),'file','keep-me'),e=>{assert(e instanceof GetNoteAPIError);assert.equal(e.operationId,'keep-me');assert.equal(e.uploadKind,'file');assert.equal(e.retryable,false);assert.match(e.recoveryAdvice,/original|原/);assert.equal(JSON.stringify(e).includes('SENSITIVE_SIGNATURE'),false);return true});assert.equal(minted,1);assert.equal(lookups,1);
|
|
37
|
+
}
|
|
38
|
+
});
|
|
39
|
+
test('credential conflict is preserved and never looked up under a different request',async t=>{
|
|
40
|
+
const paths=[];const base=await fixture(t,(req,res)=>{paths.push(req.url);if(req.url.includes('/config'))return ok(res,{runtime:runtime('image')});fail(res,'credential_operation_conflict',40902)});await assert.rejects(()=>issue(new GetNoteClient('key','client',base),'image','original'),e=>e.reason==='credential_operation_conflict'&&e.requestId==='req-operation'&&e.operationId==='original');assert.equal(paths.length,2);
|
|
41
|
+
});
|
|
42
|
+
test('issued operation with expired original deadline never returns credential',async t=>{
|
|
43
|
+
const base=await fixture(t,(req,res)=>{if(req.url.includes('/config'))return ok(res,{runtime:runtime('image')});ok(res,{operation_id:'original',state:'issued',resume_until:'2000-01-01T00:00:00Z',credential:token()})});await assert.rejects(()=>new GetNoteClient('key','client',base).getUploadOperation('original'),e=>e.reason==='credential_operation_expired'&&!JSON.stringify(e).includes('SENSITIVE_SIGNATURE'));
|
|
44
|
+
});
|
|
45
|
+
test('unconfirmed lookup preserves the issuance request ID and public error advice',async t=>{
|
|
46
|
+
const base=await fixture(t,(req,res)=>{if(req.url.includes('/config'))return ok(res,{runtime:runtime('image')});if(req.url.includes('/upload_token'))return fail(res,'credential_operation_unconfirmed');ok(res,{operation_id:'original',state:'processing',resume_until:'2099-01-01T00:00:00Z'})});await assert.rejects(()=>issue(new GetNoteClient('key','client',base),'image','original'),e=>e.requestId==='req-operation'&&e.retryable===false);
|
|
47
|
+
});
|
|
48
|
+
test('upload_image keeps original operation metadata on successful upload and OSS failure',async t=>{
|
|
49
|
+
let mode='success';let posts=0;let base;
|
|
50
|
+
base=await fixture(t,(req,res)=>{if(req.url==='/oss'){posts++;if(mode==='failure'){res.writeHead(503);return res.end('not available')}return okOSS(res)}if(req.url.includes('/config'))return ok(res,{runtime:runtime('image')});ok(res,{...token(),host:base+'/oss',accessid:'a',policy:'p',callback:'c',oss_content_type:'image/png',object_key:'same-object',operation_id:'original',resume_until:'2099-01-01T00:00:00Z'})});
|
|
51
|
+
function okOSS(res){res.setHeader('content-type','application/json');res.end(JSON.stringify({h:{c:0},c:{image:{id:'image-1'}}}))}
|
|
52
|
+
const c=new GetNoteClient('key','client',base);const success=await c.uploadImage(Buffer.from('image'),'png','original');assert.equal(success.operation_id,'original');assert.equal(success.access_url,'https://oss.test/original');mode='failure';await assert.rejects(()=>c.uploadImage(Buffer.from('image'),'png','original'),e=>e.operationId==='original'&&e.retryable===false&&!JSON.stringify(e).includes('SENSITIVE_SIGNATURE'));assert.equal(posts,2);
|
|
53
|
+
});
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
import http from 'node:http';
|
|
3
|
+
import test from 'node:test';
|
|
4
|
+
import {GetNoteClient} from '../dist/client.js';
|
|
5
|
+
|
|
6
|
+
const canonical='/open/api/v1/resource/image/upload_operation';
|
|
7
|
+
const future='2099-01-01T00:00:00Z';
|
|
8
|
+
const past='2000-01-01T00:00:00Z';
|
|
9
|
+
const runtime={governance_enabled:true,operation_replay:true,idempotency_header:'Idempotency-Key',operation_status_endpoint:canonical};
|
|
10
|
+
function ok(res,data){res.setHeader('content-type','application/json');res.end(JSON.stringify({success:true,data}));}
|
|
11
|
+
async function fixture(t,handler){const server=http.createServer(handler);await new Promise(r=>server.listen(0,'127.0.0.1',r));t.after(async()=>{server.closeAllConnections();await new Promise(r=>server.close(r))});return `http://127.0.0.1:${server.address().port}`;}
|
|
12
|
+
|
|
13
|
+
// Successful HTTP status cannot turn an expired or mismatched credential into a usable one.
|
|
14
|
+
test('successful issuance rejects expired credentials and does not relabel a different operation',async t=>{
|
|
15
|
+
for(const [name,credential,reason]of [
|
|
16
|
+
['expired',{operation_id:'original',resume_until:past},'credential_operation_expired'],
|
|
17
|
+
['mismatched',{operation_id:'other-operation',resume_until:future},'credential_operation_conflict'],
|
|
18
|
+
])await t.test(name,async t=>{
|
|
19
|
+
let issues=0,lookups=0;
|
|
20
|
+
const base=await fixture(t,(req,res)=>{
|
|
21
|
+
if(req.url.includes('/config'))return ok(res,{runtime});
|
|
22
|
+
if(req.url.includes('/upload_operation')){lookups++;return ok(res,{operation_id:'original',state:'processing',resume_until:future})}
|
|
23
|
+
issues++;ok(res,{...credential,signature:'DO_NOT_USE'});
|
|
24
|
+
});
|
|
25
|
+
await assert.rejects(()=>new GetNoteClient('key','client',base).getUploadToken({operation_id:'original',mime_type:'png'}),e=>e.reason===reason&&e.operationId==='original'&&!JSON.stringify(e).includes('DO_NOT_USE'));
|
|
26
|
+
assert.equal(issues,1);assert.equal(lookups,0);
|
|
27
|
+
});
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
// The original credential deadline is the lower bound, even if the lookup view
|
|
31
|
+
// advertises a later deadline; its identity may never be silently overwritten.
|
|
32
|
+
test('operation lookup rejects expired nested credentials and mismatched nested IDs',async t=>{
|
|
33
|
+
for(const [name,credential,reason]of [
|
|
34
|
+
['expired nested',{operation_id:'original',resume_until:past},'credential_operation_expired'],
|
|
35
|
+
['wrong nested ID',{operation_id:'different',resume_until:future},'credential_operation_conflict'],
|
|
36
|
+
])await t.test(name,async t=>{
|
|
37
|
+
let issues=0;
|
|
38
|
+
const base=await fixture(t,(req,res)=>{
|
|
39
|
+
if(req.url.includes('/config'))return ok(res,{runtime});
|
|
40
|
+
if(req.url.includes('/upload_token')){issues++;req.socket.destroy();return}
|
|
41
|
+
ok(res,{operation_id:'original',state:'issued',resume_until:future,credential:{...credential,signature:'DO_NOT_USE'}});
|
|
42
|
+
});
|
|
43
|
+
const c=new GetNoteClient('key','client',base);
|
|
44
|
+
await assert.rejects(()=>c.getUploadOperation('original'),e=>e.reason===reason&&!JSON.stringify(e).includes('DO_NOT_USE'));
|
|
45
|
+
await assert.rejects(()=>c.getUploadToken({operation_id:'original',mime_type:'png'}),e=>e.reason===reason&&e.operationId==='original');
|
|
46
|
+
assert.equal(issues,1);
|
|
47
|
+
});
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
test('recovered credential keeps its earlier original deadline',async t=>{
|
|
51
|
+
const earlier='2090-01-01T00:00:00Z';let issues=0;
|
|
52
|
+
const base=await fixture(t,(req,res)=>{
|
|
53
|
+
if(req.url.includes('/config'))return ok(res,{runtime});
|
|
54
|
+
if(req.url.includes('/upload_token')){issues++;req.socket.destroy();return}
|
|
55
|
+
ok(res,{operation_id:'original',state:'issued',resume_until:future,credential:{operation_id:'original',resume_until:earlier,object_key:'original'}});
|
|
56
|
+
});
|
|
57
|
+
const c=new GetNoteClient('key','client',base);
|
|
58
|
+
const recovered=await c.getUploadToken({operation_id:'original',mime_type:'png'});
|
|
59
|
+
assert.equal(recovered.resume_until,earlier);assert.equal(issues,1);
|
|
60
|
+
const view=await c.getUploadOperation('original');assert.equal(view.resume_until,earlier);assert.equal(view.credential.resume_until,earlier);
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
// Following a credential GET redirect would issue outside the single negotiated
|
|
64
|
+
// request and evade the lost-response lookup path.
|
|
65
|
+
test('credential redirect is not followed and only the original operation is queried',async t=>{
|
|
66
|
+
let issues=0,redirected=0,lookups=0;
|
|
67
|
+
const base=await fixture(t,(req,res)=>{
|
|
68
|
+
if(req.url.includes('/config'))return ok(res,{runtime});
|
|
69
|
+
if(req.url.includes('/upload_token')){issues++;res.writeHead(302,{Location:'/second-mint'});res.end();return}
|
|
70
|
+
if(req.url==='/second-mint'){redirected++;return ok(res,{operation_id:'original',resume_until:future,object_key:'wrong-redirect-result'})}
|
|
71
|
+
lookups++;ok(res,{operation_id:'original',state:'issued',resume_until:future,credential:{operation_id:'original',resume_until:future,object_key:'original-object'}});
|
|
72
|
+
});
|
|
73
|
+
const result=await new GetNoteClient('key','client',base).getUploadToken({operation_id:'original',mime_type:'png'});
|
|
74
|
+
assert.equal(result.object_key,'original-object');assert.equal(issues,1);assert.equal(redirected,0);assert.equal(lookups,1);
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
test('only the verified full canonical operation endpoint enables recoverable issuance',async t=>{
|
|
78
|
+
for(const endpoint of ['/resource/image/upload_operation','/api/v1/resource/image/upload_operation','/open/api/v1/resource/image/upload_operation?other=1'])await t.test(endpoint,async t=>{
|
|
79
|
+
let issues=0;
|
|
80
|
+
const base=await fixture(t,(req,res)=>{if(req.url.includes('/config'))return ok(res,{runtime:{...runtime,operation_status_endpoint:endpoint}});issues++;ok(res,{operation_id:'original',resume_until:future});});
|
|
81
|
+
await assert.rejects(()=>new GetNoteClient('key','client',base).getUploadToken({operation_id:'original',mime_type:'png'}),e=>e.reason==='upload_operation_unsupported');assert.equal(issues,0);
|
|
82
|
+
});
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
test('failed recovery lookup retains the original issuance request ID',async t=>{
|
|
86
|
+
const base=await fixture(t,(req,res)=>{
|
|
87
|
+
if(req.url.includes('/config'))return ok(res,{runtime});
|
|
88
|
+
const issuing=req.url.includes('/upload_token');
|
|
89
|
+
res.writeHead(issuing?409:503,{'content-type':'application/json'});
|
|
90
|
+
res.end(JSON.stringify({success:false,error:{code:issuing?40901:50300,reason:issuing?'credential_operation_unconfirmed':'credential_operation_unavailable',retryable:false},request_id:issuing?'original-issuance-request':'lookup-request'}));
|
|
91
|
+
});
|
|
92
|
+
await assert.rejects(()=>new GetNoteClient('key','client',base).getUploadToken({operation_id:'original',mime_type:'png'}),e=>e.operationId==='original'&&e.requestId==='original-issuance-request');
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
test('server cooldown survives a non-retryable call and blocks the next same-identity tool',async t=>{
|
|
96
|
+
let calls=0;
|
|
97
|
+
const base=await fixture(t,(req,res)=>{
|
|
98
|
+
calls++;
|
|
99
|
+
if(calls===1){res.writeHead(429,{'content-type':'application/json','retry-after':'1'});res.end(JSON.stringify({success:false,error:{code:10202,reason:'qps_global_exceeded',retryable:false,rate_limit_detail:{dimension:'qps',bucket:'global',request_execution:'admitted',retry_action:'inspect',retryable:false,retry_after_ms:200}}}));return}
|
|
100
|
+
ok(res,{id:'1'});
|
|
101
|
+
});
|
|
102
|
+
const c=new GetNoteClient('key','client',base);
|
|
103
|
+
await assert.rejects(()=>c.saveNote({content:'refused'}));
|
|
104
|
+
await assert.rejects(()=>c.withSignal(AbortSignal.timeout(30)).getNote('1'));
|
|
105
|
+
assert.equal(calls,1);
|
|
106
|
+
await new GetNoteClient('other-key','client',base).getNote('2');assert.equal(calls,2);
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
// File capabilities require topic.read while issuance requires topic.write.
|
|
110
|
+
// A write-only grant may keep legacy one-shot issuance without asserting replay.
|
|
111
|
+
test('file capability 403 keeps default write-only issuance but explicit recovery remains unsupported',async t=>{
|
|
112
|
+
let issues=0,configs=0;
|
|
113
|
+
const base=await fixture(t,(req,res)=>{
|
|
114
|
+
if(req.url.includes('/capabilities')){configs++;res.writeHead(403,{'content-type':'application/json'});res.end(JSON.stringify({success:false,error:{code:40300,reason:'insufficient_scope',message:'topic.read required',retryable:false}}));return}
|
|
115
|
+
issues++;assert.equal(req.headers['idempotency-key'],undefined);ok(res,{object_key:'legacy-write-only'});
|
|
116
|
+
});
|
|
117
|
+
const c=new GetNoteClient('key','client',base);
|
|
118
|
+
assert.equal((await c.getKnowledgeFileUploadToken('pdf')).object_key,'legacy-write-only');
|
|
119
|
+
await assert.rejects(()=>c.getKnowledgeFileUploadToken('pdf','original'),e=>e.reason==='upload_operation_unsupported');
|
|
120
|
+
assert.equal(issues,1);assert.equal(configs,1);
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
test('image configuration 403 and file configuration 503 do not permit blind issuance',async t=>{
|
|
124
|
+
for(const [kind,status]of [['image',403],['file',503]])await t.test(`${kind} ${status}`,async t=>{
|
|
125
|
+
let issues=0;
|
|
126
|
+
const base=await fixture(t,(req,res)=>{
|
|
127
|
+
if(req.url.includes('/config')||req.url.includes('/capabilities')){res.writeHead(status,{'content-type':'application/json'});res.end(JSON.stringify({success:false,error:{code:status*100,reason:'configuration_unavailable',retryable:false}}));return}
|
|
128
|
+
issues++;ok(res,{});
|
|
129
|
+
});
|
|
130
|
+
const c=new GetNoteClient('key','client',base);
|
|
131
|
+
await assert.rejects(()=>kind==='file'?c.getKnowledgeFileUploadToken('pdf'):c.getUploadToken({mime_type:'png'}));assert.equal(issues,0);
|
|
132
|
+
});
|
|
133
|
+
});
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
import http from 'node:http';
|
|
3
|
+
import test from 'node:test';
|
|
4
|
+
import {fileURLToPath} from 'node:url';
|
|
5
|
+
import {Client} from '@modelcontextprotocol/sdk/client/index.js';
|
|
6
|
+
import {StdioClientTransport} from '@modelcontextprotocol/sdk/client/stdio.js';
|
|
7
|
+
|
|
8
|
+
async function protocol(t,handler){
|
|
9
|
+
const api=http.createServer(handler);await new Promise(r=>api.listen(0,'127.0.0.1',r));
|
|
10
|
+
const client=new Client({name:'upload-v2-protocol',version:'1'});const transport=new StdioClientTransport({command:process.execPath,args:[fileURLToPath(new URL('../dist/index.js',import.meta.url))],env:{...process.env,GETNOTE_API_KEY:'key',GETNOTE_CLIENT_ID:'client',GETNOTE_API_URL:`http://127.0.0.1:${api.address().port}`},stderr:'pipe'});
|
|
11
|
+
await client.connect(transport);t.after(async()=>{await client.close();api.closeAllConnections();await new Promise(r=>api.close(r))});return client;
|
|
12
|
+
}
|
|
13
|
+
function ok(res,data){res.setHeader('content-type','application/json');res.end(JSON.stringify({success:true,data}));}
|
|
14
|
+
function runtime(kind){const prefix=kind==='image'?'/resource/image':'/resource/knowledge/file';return {governance_enabled:true,operation_replay:true,idempotency_header:'Idempotency-Key',operation_status_endpoint:'/open/api/v1'+prefix+'/upload_operation'};}
|
|
15
|
+
test('actual stdio tools expose image/file recovery and forward original operation identifiers',async t=>{
|
|
16
|
+
const received=[];const client=await protocol(t,(req,res)=>{received.push({url:req.url,key:req.headers['idempotency-key']});if(req.url.includes('/config'))return ok(res,{runtime:runtime('image')});if(req.url.includes('/capabilities'))return ok(res,{runtime:runtime('file')});if(req.url.includes('/upload_operation')){const id=new URL(req.url,'http://local').searchParams.get('operation_id');return ok(res,{operation_id:id,state:'issued',resume_until:'2099-01-01T00:00:00Z',credential:{object_key:'same-object'}})}ok(res,{object_key:'same-object',operation_id:req.headers['idempotency-key'],resume_until:'2099-01-01T00:00:00Z'})});
|
|
17
|
+
const {tools}=await client.listTools();for(const name of ['get_upload_operation','get_knowledge_file_upload_operation'])assert.ok(tools.some(tool=>tool.name===name),name);
|
|
18
|
+
for(const name of ['get_upload_token','get_knowledge_file_upload_token','upload_image'])assert.equal(tools.find(tool=>tool.name===name).inputSchema.properties.operation_id.pattern,'^[A-Za-z0-9._:-]{1,128}$');
|
|
19
|
+
for(const [name,args]of [['get_upload_token',{mime_type:'png',operation_id:'image:key'}],['get_knowledge_file_upload_token',{mime_type:'pdf',operation_id:'file:key'}],['get_upload_operation',{operation_id:'image:key'}],['get_knowledge_file_upload_operation',{operation_id:'file:key'}]]){
|
|
20
|
+
const result=await client.callTool({name,arguments:args});assert.ok(!result.isError,JSON.stringify(result));const data=JSON.parse(result.content[0].text);assert.equal(data.operation_id,args.operation_id);
|
|
21
|
+
}
|
|
22
|
+
assert.deepEqual(received.filter(r=>r.url.includes('/upload_token')).map(r=>r.key),['image:key','file:key']);
|
|
23
|
+
const before=received.length;const invalid=await client.callTool({name:'get_upload_token',arguments:{mime_type:'png',operation_id:'bad key'}});assert.equal(invalid.isError,true);assert.equal(received.length,before);
|
|
24
|
+
});
|
|
25
|
+
test('actual stdio error preserves complete future rate detail and original upload recovery advice',async t=>{
|
|
26
|
+
const detail={dimension:'day',bucket:'upload_credential',request_execution:'not_started',retry_action:'pause_until_reset',retryable:false,retry_after_seconds:3600,future:{nested:['v3',42]}};
|
|
27
|
+
const client=await protocol(t,(req,res)=>{if(req.url.includes('/config'))return ok(res,{runtime:runtime('image')});if(req.url.includes('/upload_operation'))return ok(res,{operation_id:'original',state:'processing',resume_until:'2099-01-01T00:00:00Z',credential:{signature:'SHOULD_NOT_LEAK'}});res.writeHead(429,{'content-type':'application/json','retry-after':'3600'});res.end(JSON.stringify({success:false,error:{code:10203,reason:'quota_exhausted',message:'pause',retryable:false,rate_limit_detail:detail},request_id:'req-v2-stdio'}))});
|
|
28
|
+
const refused=await client.callTool({name:'get_upload_token',arguments:{mime_type:'png',operation_id:'original'}});assert.equal(refused.isError,true);const error=JSON.parse(refused.content[0].text);assert.deepEqual(error.rate_limit_detail,detail);assert.equal(error.request_id,'req-v2-stdio');assert.equal(error.operation_id,'original');assert.equal(error.upload_kind,'image');assert.equal(error.retry_after_seconds,3600);
|
|
29
|
+
const pending=await client.callTool({name:'get_upload_operation',arguments:{operation_id:'original'}});assert.equal(pending.isError,true);const pendingError=JSON.parse(pending.content[0].text);assert.equal(pendingError.operation_id,'original');assert.equal(pendingError.retryable,false);assert.equal(pendingError.query_tool,'get_upload_operation');assert.match(pendingError.recovery_advice,/original/);assert.equal(JSON.stringify(pending).includes('SHOULD_NOT_LEAK'),false);
|
|
30
|
+
});
|