@promptframe/creation 0.3.3 → 0.3.5
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/.agents/plugins/marketplace.json +1 -1
- package/.claude-plugin/plugin.json +1 -1
- package/.codex-plugin/plugin.json +1 -1
- package/README.md +7 -1
- package/dist/cli.mjs +1452 -551
- package/docs/development.md +12 -0
- package/docs/install-guidance.json +1 -1
- package/docs/installing.md +3 -3
- package/lib/cli.mjs +6 -3
- package/lib/host-context.mjs +28 -8
- package/lib/local-upload-file.mjs +92 -0
- package/lib/local-upload-state.mjs +136 -0
- package/lib/local-upload-transfer.mjs +108 -0
- package/lib/local-upload.mjs +274 -0
- package/lib/version.mjs +1 -1
- package/package.json +1 -1
- package/skills/creation-setup/SKILL.md +2 -2
- package/skills/video-creation/SKILL.md +2 -0
package/docs/development.md
CHANGED
|
@@ -73,3 +73,15 @@ PreToolUse hook不替用户批准工具。Claude的auto模式可能先审核hook
|
|
|
73
73
|
Claude Code 使用官方 `plugin list --json` 与 `plugin marketplace list --json` 读取登记,不调用会健康检查 MCP 的 `mcp list/get`。本地 marketplace 的 `readFromFolder/folderVersion` 表示实际读取目录,其folderVersion与安装记录的缓存版本可不同;按实际目录版本和完整性核对;版本目录及两份 MCP 定义均验证摘要。每个登记写前保存阶段,回程未知后只观察原身份。隔离 CLI 安装不等于桌面模型会话加载。
|
|
74
74
|
|
|
75
75
|
标准 MCP 初始化后的图片和嵌入资源表示由平台的 `standardContentTypes` 协商启用。缺少该字段的平台继续使用文字降级;显式宿主限制优先。表示选择不改变会话身份、素材权限或业务调用次数。
|
|
76
|
+
|
|
77
|
+
## 本机文件传输
|
|
78
|
+
|
|
79
|
+
本机上传由平台目录的 `creation-local-file-upload/v1` 元数据选择,桥不按工具名称维护业务名单。模型只提供用户选择的单文件路径和原请求键;控制请求只带文件名、大小、SHA与原上传身份,字节流使用原会话的短期分片授权直达对象存储。
|
|
80
|
+
|
|
81
|
+
文件哈希和分片读取持有同一个文件描述符,并核对路径/描述符身份与变更。每桥最多两项传输,单次读取64KiB;原文件/分片/授权期限共用剩余预算。私有恢复目录为凭据配置同目录下的 `local-upload-state`,目录0700/文件0600,不保存Token、签名地址或完整文件路径。恢复缺失分片时重新选择同一文件,平台已传分片为准;不确定的PUT不自动重复。平台会话仍拥有校验、采用、配额和清理权威。
|
|
82
|
+
|
|
83
|
+
桥关闭时中止并等待本地传输、控制请求和文件IO;不隐式取消平台上传。正常取消沿原上传身份提交。每次正常访问时有界回收超过上传到期24小时的本地记录,活跃本地锁受保护;对象和已被引用资产只由平台既有生命周期清理。崩溃残留锁在Linux只凭精确boot/进程birth确认已退后恢复,其它平台无法确认时明确拒绝,不按PID猜测或自动覆盖锁。
|
|
84
|
+
|
|
85
|
+
完成阶段若已处于 `uploaded_unverified`,或已finalized但最小派生尚未入队,显式resume沿原completeKey、完整parts和原upload/asset重接complete,不请求分片resume或再次PUT。可不再选择本地文件;若同时给出文件,仍核原文件身份/内容。原会话和文件期限不延长。只读status不修复队列,丢失恢复回执后先查原状态;已确认派生存在时不再complete。返回的阶段与本桥是否仍在传输分别说明,崩溃记录不冒活跃IO。
|
|
86
|
+
|
|
87
|
+
已发PUT但缺确认的分片保持原pending身份;provider当前分片列表缺它不证明未开始,恢复不会再次PUT该分片。只有原分片后来可读的完成回执,或传输模块自身记录的真实not-dispatched,才继续缺失分片。任意错误文字不构成not-dispatched;必要时只沿原会话观察或明确取消。
|
package/docs/installing.md
CHANGED
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
|
|
7
7
|
<!-- creation-install-command -->
|
|
8
8
|
```bash
|
|
9
|
-
npx --yes @promptframe/creation@0.3.
|
|
9
|
+
npx --yes @promptframe/creation@0.3.5 connect --endpoint <Studio提供的API地址>
|
|
10
10
|
```
|
|
11
11
|
<!-- /creation-install-command -->
|
|
12
12
|
|
|
@@ -26,7 +26,7 @@ npx --yes @promptframe/creation@0.3.3 connect --endpoint <Studio提供的API地
|
|
|
26
26
|
|
|
27
27
|
<!-- creation-install-command -->
|
|
28
28
|
```bash
|
|
29
|
-
npx --yes @promptframe/creation@0.3.
|
|
29
|
+
npx --yes @promptframe/creation@0.3.5 connect --host claude-code --endpoint <Studio提供的API地址>
|
|
30
30
|
```
|
|
31
31
|
<!-- /creation-install-command -->
|
|
32
32
|
|
|
@@ -46,7 +46,7 @@ CLI 优先使用 PATH 中的 Claude;桌面版远程连接 WSL 时,也识别
|
|
|
46
46
|
|
|
47
47
|
<!-- creation-install-command -->
|
|
48
48
|
```bash
|
|
49
|
-
npx --yes @promptframe/creation@0.3.
|
|
49
|
+
npx --yes @promptframe/creation@0.3.5 connect --profile work-account --endpoint <另一环境API地址>
|
|
50
50
|
```
|
|
51
51
|
<!-- /creation-install-command -->
|
|
52
52
|
|
package/lib/cli.mjs
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
+
import {createLocalUploadManager} from './local-upload.mjs';
|
|
2
3
|
import {CLIENT_VERSION} from "./version.mjs";
|
|
3
4
|
import { randomBytes } from "node:crypto";
|
|
4
5
|
import { spawn } from "node:child_process";
|
|
@@ -199,7 +200,8 @@ async function bridge() {
|
|
|
199
200
|
experimental:{...(policy?{'promptframe.creation':policy}:{}),
|
|
200
201
|
'promptframe.runtime':{version:selection.version,locked:selection.locked,status:selection.status}} } },
|
|
201
202
|
),
|
|
202
|
-
host=createHostCallBridge(client,{credentials,host:identity,hostSession,
|
|
203
|
+
host=createHostCallBridge(client,{credentials,host:identity,hostSession,
|
|
204
|
+
localUploads:createLocalUploadManager({stateRoot:path.join(path.dirname(configFile()),'local-upload-state')}),onCatalogChange:()=>server.sendToolListChanged(),
|
|
203
205
|
onKnowledgeChange:kind=>kind==='resources'?server.sendResourceListChanged():server.sendPromptListChanged()});
|
|
204
206
|
server.oninitialized=()=>{const declared=declaredHostContentCapabilities(server.getClientCapabilities(),
|
|
205
207
|
{initialized:true,standardContent:!!policy?.standardContentTypes});
|
|
@@ -232,9 +234,9 @@ async function bridge() {
|
|
|
232
234
|
throw new Error("creation.connection_unresolved");
|
|
233
235
|
}
|
|
234
236
|
});
|
|
235
|
-
server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
237
|
+
server.setRequestHandler(CallToolRequestSchema, async (request,extra) => {
|
|
236
238
|
try {
|
|
237
|
-
return await host.call(request.params);
|
|
239
|
+
return await host.call(request.params,{signal:extra.signal});
|
|
238
240
|
} catch (error) {
|
|
239
241
|
return {
|
|
240
242
|
isError: true,
|
|
@@ -264,6 +266,7 @@ async function bridge() {
|
|
|
264
266
|
const close = async () => {
|
|
265
267
|
if (closing) return;
|
|
266
268
|
closing = true;
|
|
269
|
+
await host.close();
|
|
267
270
|
await server.close().catch(() => {});
|
|
268
271
|
await client.close().catch(() => {});
|
|
269
272
|
};
|
package/lib/host-context.mjs
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import {LOCAL_UPLOAD_PROTOCOL} from './local-upload.mjs';
|
|
1
2
|
import {createHash} from 'node:crypto';
|
|
2
3
|
import {CreationClientError} from './credentials.mjs';
|
|
3
4
|
import {hostParameters,resolveHostIdentity} from './host-identity.mjs';
|
|
@@ -20,7 +21,7 @@ const boundedSet=(map,key,value)=>{if(!map.has(key)&&map.size>=1024)map.delete(m
|
|
|
20
21
|
|
|
21
22
|
/** The authenticated platform owns classification and editor authority.
|
|
22
23
|
* Business text and model annotations never populate this cache. */
|
|
23
|
-
export function createHostCallBridge(client,{credentials,host=resolveHostIdentity(),hostSession,onCatalogChange=()=>{},onKnowledgeChange=()=>{}}={}){
|
|
24
|
+
export function createHostCallBridge(client,{credentials,host=resolveHostIdentity(),hostSession,localUploads,onCatalogChange=()=>{},onKnowledgeChange=()=>{}}={}){
|
|
24
25
|
if(!credentials?.endpoint||!credentials.clientId)throw new CreationClientError('creation.bridge_identity_required');
|
|
25
26
|
const installationDigest=digest(credentials.clientId);
|
|
26
27
|
const versions=new Map(),controllers=new Map(),catalogs=new Map(),inflight=new Map();
|
|
@@ -70,9 +71,9 @@ export function createHostCallBridge(client,{credentials,host=resolveHostIdentit
|
|
|
70
71
|
}
|
|
71
72
|
return v;
|
|
72
73
|
}
|
|
73
|
-
async function send(params,binding){
|
|
74
|
+
async function send(params,binding,{signal,timeout=60000}={}){
|
|
74
75
|
await binding?.assertCurrent();
|
|
75
|
-
const order=++sequence,result=assertMcpResponseBudget(await client.callTool(params,undefined,{timeout:
|
|
76
|
+
const order=++sequence,result=assertMcpResponseBudget(await client.callTool(params,undefined,{timeout,...(signal?{signal}:{})}));
|
|
76
77
|
await binding?.assertCurrent();
|
|
77
78
|
return {result,trusted:remember(params,result,order)};
|
|
78
79
|
}
|
|
@@ -82,12 +83,15 @@ export function createHostCallBridge(client,{credentials,host=resolveHostIdentit
|
|
|
82
83
|
if(!directory||order>=directory.order)directory={tools:new Map(result.tools.map(t=>[t.name,t])),order};
|
|
83
84
|
catalog('outer',result._meta?.['promptframe.catalogVersion'],order);
|
|
84
85
|
return {...result,tools:result.tools.map(tool=>{
|
|
85
|
-
const
|
|
86
|
+
const local=tool._meta?.['promptframe.localFileUpload'];
|
|
87
|
+
const schema=local?.contractVersion===LOCAL_UPLOAD_PROTOCOL?local.inputSchema:tool.inputSchema;
|
|
88
|
+
if(!schema||schema.type!=='object')throw new CreationClientError('creation.upgrade_required');
|
|
89
|
+
const p=schema.properties;
|
|
86
90
|
const {controlVersion:_managed,...properties}=p??{};
|
|
87
|
-
return {...tool,inputSchema:{...
|
|
91
|
+
return {...tool,inputSchema:{...schema,properties:{...properties,...(host.kind==='claude-code'?{
|
|
88
92
|
[CLAUDE_HOST_PROOF]:{type:'string',pattern:'^[a-f0-9]{64}$',description:'由当前宿主hook填入的单次身份凭证;请保留,不自行填写。'}
|
|
89
|
-
}:{})},...(
|
|
90
|
-
?{required:
|
|
93
|
+
}:{})},...(schema.required
|
|
94
|
+
?{required:schema.required.filter(name=>name!=='controlVersion')}:{})}};
|
|
91
95
|
})};
|
|
92
96
|
}
|
|
93
97
|
async function ensureDirectory(){
|
|
@@ -129,7 +133,7 @@ export function createHostCallBridge(client,{credentials,host=resolveHostIdentit
|
|
|
129
133
|
listResourceTemplates:params=>knowledgeRead('resources','listResourceTemplates',params),
|
|
130
134
|
readResource:params=>knowledgeRead('resources','readResource',params),
|
|
131
135
|
listPrompts:params=>knowledgeRead('prompts','listPrompts',params),
|
|
132
|
-
getPrompt:params=>knowledgeRead('prompts','getPrompt',params),async call(raw){
|
|
136
|
+
getPrompt:params=>knowledgeRead('prompts','getPrompt',params),close:()=>localUploads?.close(),async call(raw,{signal}={}){
|
|
133
137
|
for(const field of ['threadId','controller','clientDigest','token','controlVersion'])if(Object.hasOwn(raw.arguments??{},field))
|
|
134
138
|
throw new CreationClientError('creation.transport_authority_managed_by_bridge');
|
|
135
139
|
let binding={host,arguments:raw.arguments,assertCurrent:async()=>{}};
|
|
@@ -163,6 +167,22 @@ export function createHostCallBridge(client,{credentials,host=resolveHostIdentit
|
|
|
163
167
|
resolvedControl=observed.trusted?.control;
|
|
164
168
|
}
|
|
165
169
|
hostParameters(raw,binding.host,effectiveAccess);
|
|
170
|
+
const local=definition._meta['promptframe.localFileUpload'];
|
|
171
|
+
if(local?.contractVersion===LOCAL_UPLOAD_PROTOCOL){
|
|
172
|
+
if(!localUploads)throw new CreationClientError('creation.upgrade_required');
|
|
173
|
+
// Resolve account/platform and the live work from an authenticated read,
|
|
174
|
+
// without taking its editor or starting any business execution.
|
|
175
|
+
const {projectId,sessionId}=params.arguments??{};
|
|
176
|
+
if(typeof projectId!=='string'||typeof sessionId!=='string')throw new CreationClientError('creation.request_invalid');
|
|
177
|
+
const observed=await send({name:role('control-read'),_meta:params._meta,arguments:{projectId,sessionId,pageSize:1}},binding);
|
|
178
|
+
if(observed.result.isError)return observed.result;
|
|
179
|
+
if(!observed.trusted)throw new CreationClientError('creation.access_unverified');
|
|
180
|
+
const value=await localUploads.call({input:params.arguments,binding,signal,scope:{platform:observed.trusted.platformDigest,
|
|
181
|
+
account:observed.trusted.accountDigest,installation:installationDigest,host:binding.host.kind,
|
|
182
|
+
thread:params._meta.threadId.toLowerCase(),projectId,sessionId},
|
|
183
|
+
send:(transfer,options)=>send({name:params.name,_meta:params._meta,arguments:{projectId,sessionId,transfer}},binding,{timeout:30000,...options})});
|
|
184
|
+
return assertMcpResponseBudget({content:[{type:'text',text:JSON.stringify(value)}]});
|
|
185
|
+
}
|
|
166
186
|
const key=keyFor(params);let outgoing=params;
|
|
167
187
|
if(managed){
|
|
168
188
|
if(!key){
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import {constants} from 'node:fs';
|
|
2
|
+
import {open,lstat} from 'node:fs/promises';
|
|
3
|
+
import {createHash} from 'node:crypto';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import {Readable} from 'node:stream';
|
|
6
|
+
import {finished} from 'node:stream/promises';
|
|
7
|
+
import {CreationClientError} from './credentials.mjs';
|
|
8
|
+
|
|
9
|
+
export const LOCAL_UPLOAD_MAX_BYTES=2*1024**3;
|
|
10
|
+
export const LOCAL_UPLOAD_READ_BYTES=64*1024;
|
|
11
|
+
const fingerprint=stat=>({dev:String(stat.dev),ino:String(stat.ino),sizeBytes:Number(stat.size),
|
|
12
|
+
mtimeNs:String(stat.mtimeNs),ctimeNs:String(stat.ctimeNs)});
|
|
13
|
+
const equal=(left,right)=>Object.keys(left).every(key=>left[key]===right[key]);
|
|
14
|
+
const failure=code=>new CreationClientError('creation.local_upload.'+code);
|
|
15
|
+
|
|
16
|
+
/** Open only the selected file. Retain the same descriptor through hashing and
|
|
17
|
+
* transport; the platform still owns the upload, checksum and asset decision. */
|
|
18
|
+
export async function openLocalUploadFile(selectedPath,{maxBytes=LOCAL_UPLOAD_MAX_BYTES,signal,deadlineAtMs=Infinity,now=Date.now}={}){
|
|
19
|
+
if(typeof selectedPath!=='string'||!selectedPath||selectedPath.includes('\0')
|
|
20
|
+
||!Number.isSafeInteger(maxBytes)||maxBytes<1||maxBytes>LOCAL_UPLOAD_MAX_BYTES)
|
|
21
|
+
throw failure('file_selection_invalid');
|
|
22
|
+
if(process.platform!=='win32'&&/^(?:[a-z]:[\\/]|\\\\)/i.test(selectedPath))
|
|
23
|
+
throw failure('path_not_on_bridge_host');
|
|
24
|
+
const selected=path.resolve(selectedPath),name=path.basename(selected);
|
|
25
|
+
if(name.length>512||/[\x00-\x1f\x7f]/.test(name))throw failure('file_selection_invalid');
|
|
26
|
+
let handle;
|
|
27
|
+
try{handle=await open(selected,constants.O_RDONLY|constants.O_NOFOLLOW|constants.O_NONBLOCK);}
|
|
28
|
+
catch(error){throw failure(error.code==='ELOOP'?'file_not_regular'
|
|
29
|
+
:error.code==='EACCES'||error.code==='EPERM'?'file_read_denied':'file_not_on_bridge_host');}
|
|
30
|
+
const abort=new AbortController(),streams=new Map(),reads=new Set();
|
|
31
|
+
let closing=false,closed=false,original,closePromise;
|
|
32
|
+
const checkSignal=other=>{
|
|
33
|
+
if(closing||closed)throw failure('file_closed');
|
|
34
|
+
if(signal?.aborted||other?.aborted||abort.signal.aborted)throw failure('file_read_cancelled');
|
|
35
|
+
if(now()>=deadlineAtMs)throw failure('file_read_timeout');
|
|
36
|
+
};
|
|
37
|
+
const read=async(buffer,offset,length,position)=>{
|
|
38
|
+
const pending=handle.read(buffer,offset,length,position);reads.add(pending);
|
|
39
|
+
try{return await pending;}catch{throw failure('file_read_failed');}finally{reads.delete(pending);}
|
|
40
|
+
};
|
|
41
|
+
const assertUnchanged=async()=>{
|
|
42
|
+
checkSignal();
|
|
43
|
+
try{
|
|
44
|
+
const [current,named]=await Promise.all([handle.stat({bigint:true}),lstat(selected,{bigint:true})]);
|
|
45
|
+
if(!current.isFile()||!named.isFile()||!equal(original,fingerprint(current))
|
|
46
|
+
||!equal(original,fingerprint(named)))throw failure('file_changed');
|
|
47
|
+
}catch(error){if(error instanceof CreationClientError)throw error;throw failure('file_changed');}
|
|
48
|
+
};
|
|
49
|
+
const close=()=>closePromise??=(async()=>{
|
|
50
|
+
closing=true;abort.abort();
|
|
51
|
+
for(const stream of streams.keys())stream.destroy(failure('file_read_cancelled'));
|
|
52
|
+
await Promise.allSettled([...streams.values(),...reads]);
|
|
53
|
+
await handle.close();closed=true;
|
|
54
|
+
})();
|
|
55
|
+
try{
|
|
56
|
+
checkSignal();const stat=await handle.stat({bigint:true});
|
|
57
|
+
if(!stat.isFile())throw failure('file_not_regular');
|
|
58
|
+
if(stat.size<=0n||stat.size>BigInt(maxBytes))throw failure('file_size_limit');
|
|
59
|
+
original=fingerprint(stat);await assertUnchanged();
|
|
60
|
+
const hash=createHash('sha256'),buffer=Buffer.allocUnsafe(LOCAL_UPLOAD_READ_BYTES);
|
|
61
|
+
for(let position=0;position<original.sizeBytes;){
|
|
62
|
+
checkSignal();const length=Math.min(buffer.length,original.sizeBytes-position);
|
|
63
|
+
const {bytesRead}=await read(buffer,0,length,position);
|
|
64
|
+
if(bytesRead===0)throw failure('file_changed');
|
|
65
|
+
hash.update(buffer.subarray(0,bytesRead));position+=bytesRead;
|
|
66
|
+
}
|
|
67
|
+
await assertUnchanged();const checksum='sha256:'+hash.digest('hex');
|
|
68
|
+
return {
|
|
69
|
+
name,sizeBytes:original.sizeBytes,checksum,fingerprint:{...original,checksum},
|
|
70
|
+
assertUnchanged,close,
|
|
71
|
+
streamPart({start,sizeBytes,signal:partSignal}={}){
|
|
72
|
+
checkSignal(partSignal);
|
|
73
|
+
if(!Number.isSafeInteger(start)||!Number.isSafeInteger(sizeBytes)||start<0||sizeBytes<1
|
|
74
|
+
||start+sizeBytes>original.sizeBytes)throw failure('part_range_invalid');
|
|
75
|
+
async function* chunks(){
|
|
76
|
+
await assertUnchanged();let position=start;
|
|
77
|
+
while(position<start+sizeBytes){
|
|
78
|
+
checkSignal(partSignal);const bytes=Buffer.allocUnsafe(Math.min(LOCAL_UPLOAD_READ_BYTES,start+sizeBytes-position));
|
|
79
|
+
const result=await read(bytes,0,bytes.length,position);
|
|
80
|
+
checkSignal(partSignal);if(result.bytesRead===0)throw failure('file_changed');
|
|
81
|
+
position+=result.bytesRead;yield bytes.subarray(0,result.bytesRead);
|
|
82
|
+
}
|
|
83
|
+
await assertUnchanged();
|
|
84
|
+
}
|
|
85
|
+
const stream=Readable.from(chunks(),{objectMode:false,highWaterMark:LOCAL_UPLOAD_READ_BYTES});
|
|
86
|
+
const done=finished(stream).finally(()=>streams.delete(stream));
|
|
87
|
+
// A caller may cancel before it starts consuming the body.
|
|
88
|
+
done.catch(()=>{});streams.set(stream,done);return stream;
|
|
89
|
+
},
|
|
90
|
+
};
|
|
91
|
+
}catch(error){await close();if(error instanceof CreationClientError)throw error;throw failure('file_read_failed');}
|
|
92
|
+
}
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import {constants} from 'node:fs';
|
|
2
|
+
import {open,mkdir,lstat,rename,unlink,rmdir,readdir,readFile} from 'node:fs/promises';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import {randomBytes} from 'node:crypto';
|
|
5
|
+
import {CreationClientError} from './credentials.mjs';
|
|
6
|
+
|
|
7
|
+
const fail=()=>{throw new CreationClientError('creation.local_upload.recovery_state_unavailable');};
|
|
8
|
+
const flags=constants.O_NOFOLLOW;
|
|
9
|
+
const maxBytes=1024*1024,maxRecords=100,retentionMs=24*60*60*1000;
|
|
10
|
+
async function directory(root){
|
|
11
|
+
try{await mkdir(root,{mode:0o700});}catch(e){if(e.code!=='EEXIST')throw e;}
|
|
12
|
+
const info=await lstat(root);
|
|
13
|
+
if(!info.isDirectory()||info.isSymbolicLink()||(info.mode&0o077)||process.getuid&&info.uid!==process.getuid())fail();
|
|
14
|
+
}
|
|
15
|
+
async function read(file){
|
|
16
|
+
let fd;
|
|
17
|
+
try{
|
|
18
|
+
fd=await open(file,constants.O_RDONLY|flags);const info=await fd.stat();
|
|
19
|
+
if(!info.isFile()||(info.mode&0o077)||info.size>maxBytes||process.getuid&&info.uid!==process.getuid())fail();
|
|
20
|
+
return JSON.parse(await fd.readFile('utf8'));
|
|
21
|
+
}catch(e){if(e.code==='ENOENT')return null;fail();}finally{await fd?.close();}
|
|
22
|
+
}
|
|
23
|
+
async function syncDirectory(root){
|
|
24
|
+
// Windows does not expose POSIX directory fsync. File sync still precedes
|
|
25
|
+
// rename; an uncertain crash record is observed through the original key.
|
|
26
|
+
if(process.platform==='win32')return;
|
|
27
|
+
const fd=await open(root,constants.O_RDONLY|constants.O_DIRECTORY|flags);
|
|
28
|
+
try{await fd.sync();}finally{await fd.close();}
|
|
29
|
+
}
|
|
30
|
+
async function birth(pid){
|
|
31
|
+
if(process.platform!=='linux')return null;
|
|
32
|
+
try{
|
|
33
|
+
const stat=await readFile(`/proc/${pid}/stat`,'utf8'),end=stat.lastIndexOf(')');
|
|
34
|
+
return{boot:(await readFile('/proc/sys/kernel/random/boot_id','utf8')).trim(),start:stat.slice(end+2).split(' ')[19]};
|
|
35
|
+
}catch(e){if(e.code==='ENOENT')return false;fail();}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Private transport recovery only. The platform upload session remains the
|
|
39
|
+
* business authority. No credentials, paths or signed grants are stored. */
|
|
40
|
+
export async function localUploadState(root,{now=Date.now}={}){
|
|
41
|
+
try{await directory(root);}catch{fail();}
|
|
42
|
+
const ownBirth=await birth(process.pid),owner={pid:process.pid,birth:ownBirth,nonce:randomBytes(16).toString('hex')};
|
|
43
|
+
const file=key=>{if(!/^[a-f0-9]{64}$/.test(key))fail();return path.join(root,key+'.json');};
|
|
44
|
+
async function write(key,value){
|
|
45
|
+
const body=JSON.stringify(value);if(Buffer.byteLength(body)>maxBytes)fail();
|
|
46
|
+
const destination=file(key),temporary=path.join(root,key+'-'+randomBytes(12).toString('hex')+'.partial');
|
|
47
|
+
let fd;
|
|
48
|
+
try{fd=await open(temporary,constants.O_WRONLY|constants.O_CREAT|constants.O_EXCL|flags,0o600);
|
|
49
|
+
await fd.writeFile(body);await fd.sync();await fd.close();fd=undefined;
|
|
50
|
+
const current=await lstat(destination).catch(e=>{if(e.code!=='ENOENT')throw e;});
|
|
51
|
+
if(current&&(!current.isFile()||current.isSymbolicLink()||(current.mode&0o077)))fail();
|
|
52
|
+
await rename(temporary,destination);await syncDirectory(root);
|
|
53
|
+
}catch{fail();}finally{await fd?.close();await unlink(temporary).catch(()=>{});}
|
|
54
|
+
}
|
|
55
|
+
async function lock(key){
|
|
56
|
+
const target=path.join(root,key+'.lock');file(key);
|
|
57
|
+
const reclaiming=async()=> (await readdir(root)).some(name=>name.startsWith(key+'.reclaim-'));
|
|
58
|
+
for(let attempt=0;attempt<2;attempt++){
|
|
59
|
+
if(await reclaiming())throw new CreationClientError('creation.local_upload.transfer_owned_by_another_bridge');
|
|
60
|
+
const staging=path.join(root,key+'-'+randomBytes(12).toString('hex')+'.claim');
|
|
61
|
+
await mkdir(staging,{mode:0o700});
|
|
62
|
+
const prepared=await open(path.join(staging,'owner.json'),constants.O_WRONLY|constants.O_CREAT|constants.O_EXCL|flags,0o600);
|
|
63
|
+
try{await prepared.writeFile(JSON.stringify(owner));await prepared.sync();}finally{await prepared.close();}
|
|
64
|
+
await syncDirectory(staging);
|
|
65
|
+
try{await rename(staging,target);}
|
|
66
|
+
|
|
67
|
+
catch(e){
|
|
68
|
+
await unlink(path.join(staging,'owner.json'));await rmdir(staging);
|
|
69
|
+
if(!['EEXIST','ENOTEMPTY'].includes(e.code))fail();
|
|
70
|
+
const info=await lstat(target);if(!info.isDirectory()||info.isSymbolicLink()||(info.mode&0o077))fail();
|
|
71
|
+
const old=await read(path.join(target,'owner.json'));
|
|
72
|
+
if(!old||!Number.isSafeInteger(old.pid)||old.pid<1||!old.birth||process.platform!=='linux')
|
|
73
|
+
throw new CreationClientError('creation.local_upload.transfer_owned_by_another_bridge');
|
|
74
|
+
const current=await birth(old.pid);
|
|
75
|
+
if(current&¤t.boot===old.birth.boot&¤t.start===old.birth.start)
|
|
76
|
+
throw new CreationClientError('creation.local_upload.transfer_owned_by_another_bridge');
|
|
77
|
+
// Serialize retirement of this exact dead birth. Contenders check the
|
|
78
|
+
// marker again after acquiring, before any state or transport effect.
|
|
79
|
+
if(!/^[a-f0-9]{32}$/.test(old.nonce))fail();
|
|
80
|
+
const marker=path.join(root,key+'.reclaim-'+old.nonce);
|
|
81
|
+
try{await mkdir(marker,{mode:0o700});}catch{throw new CreationClientError('creation.local_upload.transfer_owned_by_another_bridge');}
|
|
82
|
+
try{
|
|
83
|
+
const again=await read(path.join(target,'owner.json'));
|
|
84
|
+
if(JSON.stringify(again)!==JSON.stringify(old))fail();
|
|
85
|
+
await unlink(path.join(target,'owner.json'));await rmdir(target);await syncDirectory(root);
|
|
86
|
+
}finally{await rmdir(marker);await syncDirectory(root);}
|
|
87
|
+
continue;
|
|
88
|
+
}
|
|
89
|
+
if(await reclaiming()){
|
|
90
|
+
const current=await read(path.join(target,'owner.json'));if(current?.nonce!==owner.nonce)fail();
|
|
91
|
+
await unlink(path.join(target,'owner.json'));await rmdir(target);
|
|
92
|
+
throw new CreationClientError('creation.local_upload.transfer_owned_by_another_bridge');
|
|
93
|
+
}
|
|
94
|
+
await syncDirectory(root);
|
|
95
|
+
return async()=>{
|
|
96
|
+
const current=await read(path.join(target,'owner.json'));
|
|
97
|
+
if(current?.nonce!==owner.nonce)fail();
|
|
98
|
+
await unlink(path.join(target,'owner.json'));await rmdir(target);await syncDirectory(root);
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
fail();
|
|
102
|
+
}
|
|
103
|
+
async function cleanup({admitNew=false}={}){
|
|
104
|
+
const names=await readdir(root);let records=0;
|
|
105
|
+
for(const name of names){
|
|
106
|
+
if(/^[a-f0-9]{64}\.json$/.test(name)){
|
|
107
|
+
const key=name.slice(0,-5),value=await read(file(key));records++;
|
|
108
|
+
const cutoff=Date.parse(value?.expiresAt??'')+retentionMs;
|
|
109
|
+
if(!Number.isFinite(cutoff)||now()<cutoff)continue;
|
|
110
|
+
let release;
|
|
111
|
+
try{release=await lock(key);}catch(e){if(e instanceof CreationClientError)continue;throw e;}
|
|
112
|
+
try{const latest=await read(file(key));if(JSON.stringify(latest)===JSON.stringify(value)){await unlink(file(key));records--;}}
|
|
113
|
+
finally{await release();}
|
|
114
|
+
}else if(/^[a-f0-9]{64}-[a-f0-9]{24}\.claim$/.test(name)){
|
|
115
|
+
const target=path.join(root,name),info=await lstat(target);
|
|
116
|
+
if(!info.isDirectory()||info.isSymbolicLink()||(info.mode&0o077)||now()-info.mtimeMs<=retentionMs)continue;
|
|
117
|
+
const old=await read(path.join(target,'owner.json'));
|
|
118
|
+
if(!old||process.platform!=='linux')continue;
|
|
119
|
+
const current=await birth(old.pid);
|
|
120
|
+
if(current&¤t.boot===old.birth?.boot&¤t.start===old.birth?.start)continue;
|
|
121
|
+
if(JSON.stringify(await read(path.join(target,'owner.json')))!==JSON.stringify(old))continue;
|
|
122
|
+
await unlink(path.join(target,'owner.json'));await rmdir(target);
|
|
123
|
+
}else if(/^[a-f0-9]{64}-[a-f0-9]{24}\.partial$/.test(name)){
|
|
124
|
+
const info=await lstat(path.join(root,name));
|
|
125
|
+
if(info.isFile()&&!info.isSymbolicLink()&&(!process.getuid||info.uid===process.getuid())
|
|
126
|
+
&&!(info.mode&0o077)&&now()-info.mtimeMs>retentionMs){
|
|
127
|
+
let release;try{release=await lock(name.slice(0,64));}catch{continue;}
|
|
128
|
+
try{await unlink(path.join(root,name));}finally{await release();}
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
await syncDirectory(root);
|
|
133
|
+
if(admitNew&&records>=maxRecords)throw new CreationClientError('creation.local_upload.local_recovery_limit');
|
|
134
|
+
}
|
|
135
|
+
return{read:async key=>read(file(key)),write,lock,cleanup};
|
|
136
|
+
}
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import {Readable} from 'node:stream';
|
|
2
|
+
import {finished} from 'node:stream/promises';
|
|
3
|
+
import {CreationClientError} from './credentials.mjs';
|
|
4
|
+
import {LOCAL_UPLOAD_READ_BYTES} from './local-upload-file.mjs';
|
|
5
|
+
|
|
6
|
+
const fail=code=>{throw new CreationClientError('creation.local_upload.'+code);};
|
|
7
|
+
const positive=value=>Number.isSafeInteger(value)&&value>0;
|
|
8
|
+
const forbiddenHeader=/^(?:authorization|cookie|host|connection|upgrade|proxy-.*)$/i;
|
|
9
|
+
const defaultBudget={totalMs:300_000,firstProgressMs:30_000,idleMs:60_000};
|
|
10
|
+
|
|
11
|
+
/** Consume an authenticated platform grant, never a model-supplied destination.
|
|
12
|
+
* A successful PUT is a part receipt; asset readiness belongs to the platform. */
|
|
13
|
+
async function transferGrantedPart(file,authorization,grant,{
|
|
14
|
+
expectedUploadId,expectedAssetId,signal,deadlineAtMs=Infinity,
|
|
15
|
+
fetch:fetchPart=globalThis.fetch,now=Date.now,onProgress=()=>{},
|
|
16
|
+
}={}){
|
|
17
|
+
const session=authorization?.session;
|
|
18
|
+
if(authorization?.contractVersion!=='direct-object-upload.v2'
|
|
19
|
+
||!session||session.uploadId!==expectedUploadId||session.assetId!==expectedAssetId
|
|
20
|
+
||session.sizeBytes!==file.sizeBytes||session.expectedChecksum!==file.checksum
|
|
21
|
+
||!positive(session.partSizeBytes)||!positive(session.partCount)
|
|
22
|
+
||session.partCount!==Math.ceil(file.sizeBytes/session.partSizeBytes)
|
|
23
|
+
||!['authorized','uploading'].includes(session.state))fail('authorization_invalid');
|
|
24
|
+
if(!grant||grant.method!=='PUT'||grant.uploadId!==expectedUploadId||grant.assetId!==expectedAssetId
|
|
25
|
+
||!positive(grant.partNumber)||grant.partNumber>session.partCount
|
|
26
|
+
||!Array.isArray(authorization.grants)
|
|
27
|
+
||authorization.grants.filter(item=>item===grant).length!==1)fail('grant_invalid');
|
|
28
|
+
let destination;
|
|
29
|
+
try{destination=new URL(grant.url);}catch{fail('grant_invalid');}
|
|
30
|
+
if(!['https:','http:'].includes(destination.protocol)||destination.username||destination.password
|
|
31
|
+
||destination.hash||grant.url.length>16*1024)fail('grant_invalid');
|
|
32
|
+
const expires=[Date.parse(grant.expiresAt),Date.parse(session.expiresAt)];
|
|
33
|
+
if(expires.some(value=>!Number.isFinite(value)))fail('grant_invalid');
|
|
34
|
+
if(expires.some(value=>value<=now()))fail('grant_expired');
|
|
35
|
+
const budget=authorization.transferBudget?.part??defaultBudget;
|
|
36
|
+
if(!positive(budget.totalMs)||budget.totalMs>300_000||!positive(budget.firstProgressMs)
|
|
37
|
+
||budget.firstProgressMs>120_000||!positive(budget.idleMs)||budget.idleMs>120_000)
|
|
38
|
+
fail('transfer_budget_invalid');
|
|
39
|
+
const start=(grant.partNumber-1)*session.partSizeBytes;
|
|
40
|
+
const sizeBytes=Math.min(session.partSizeBytes,file.sizeBytes-start);
|
|
41
|
+
const headers=new Headers();
|
|
42
|
+
if(!grant.requiredHeaders||typeof grant.requiredHeaders!=='object'||Array.isArray(grant.requiredHeaders)
|
|
43
|
+
||Object.keys(grant.requiredHeaders).length>64)fail('grant_invalid');
|
|
44
|
+
for(const [name,value] of Object.entries(grant.requiredHeaders)){
|
|
45
|
+
if(typeof value!=='string'||value.length>8192||forbiddenHeader.test(name))fail('grant_invalid');
|
|
46
|
+
try{headers.set(name,value);}catch{fail('grant_invalid');}
|
|
47
|
+
}
|
|
48
|
+
if(headers.has('content-length')&&headers.get('content-length')!==String(sizeBytes))fail('grant_invalid');
|
|
49
|
+
headers.set('content-length',String(sizeBytes));
|
|
50
|
+
const deadline=Math.min(now()+budget.totalMs,...expires,deadlineAtMs);
|
|
51
|
+
if(!Number.isFinite(deadline)||deadline<=now())fail('transfer_deadline_expired');
|
|
52
|
+
await file.assertUnchanged();
|
|
53
|
+
if(signal?.aborted)fail('transfer_cancelled');
|
|
54
|
+
const controller=new AbortController();let reason,firstTimer,idleTimer,totalTimer,bytesRead=0;
|
|
55
|
+
const abort=code=>{reason??=code;controller.abort();};
|
|
56
|
+
const cancel=()=>abort('transfer_cancelled');
|
|
57
|
+
if(signal?.aborted)cancel();else signal?.addEventListener('abort',cancel,{once:true});
|
|
58
|
+
const timer=(callback,ms)=>{const id=setTimeout(callback,ms);id.unref?.();return id;};
|
|
59
|
+
firstTimer=timer(()=>abort('transfer_first_progress_timeout'),budget.firstProgressMs);
|
|
60
|
+
totalTimer=timer(()=>abort('transfer_timeout'),Math.max(1,deadline-now()));
|
|
61
|
+
let input,body,bodyDone,inputDone,response;
|
|
62
|
+
async function* chunks(){
|
|
63
|
+
for await(const chunk of input){
|
|
64
|
+
if(controller.signal.aborted)fail(reason??'transfer_cancelled');
|
|
65
|
+
clearTimeout(firstTimer);clearTimeout(idleTimer);
|
|
66
|
+
idleTimer=timer(()=>abort('transfer_idle_timeout'),budget.idleMs);
|
|
67
|
+
bytesRead+=chunk.length;onProgress({partNumber:grant.partNumber,bytesRead,sizeBytes});
|
|
68
|
+
yield chunk;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
try{
|
|
72
|
+
input=file.streamPart({start,sizeBytes,signal:controller.signal});
|
|
73
|
+
body=Readable.from(chunks(),{objectMode:false,highWaterMark:LOCAL_UPLOAD_READ_BYTES});
|
|
74
|
+
bodyDone=finished(body);bodyDone.catch(()=>{});
|
|
75
|
+
inputDone=finished(input);inputDone.catch(()=>{});
|
|
76
|
+
response=await fetchPart(destination,{method:'PUT',headers,body,duplex:'half',redirect:'error',signal:controller.signal});
|
|
77
|
+
if(!response.ok)fail('part_target_rejected');
|
|
78
|
+
await bodyDone;await inputDone;
|
|
79
|
+
if(bytesRead!==sizeBytes)fail('part_transfer_unconfirmed');
|
|
80
|
+
await file.assertUnchanged();
|
|
81
|
+
const etag=response.headers.get('etag');
|
|
82
|
+
if(!etag||etag.length>512||/[\x00-\x1f\x7f]/.test(etag))fail('part_receipt_unconfirmed');
|
|
83
|
+
return {partNumber:grant.partNumber,etag,sizeBytes};
|
|
84
|
+
}catch(error){
|
|
85
|
+
if(reason)fail(reason);
|
|
86
|
+
if(error instanceof CreationClientError)throw error;
|
|
87
|
+
// Fetch errors can include the signed URL. Keep only a safe classification.
|
|
88
|
+
fail('part_transfer_unconfirmed');
|
|
89
|
+
}finally{
|
|
90
|
+
controller.abort();clearTimeout(firstTimer);clearTimeout(idleTimer);clearTimeout(totalTimer);
|
|
91
|
+
signal?.removeEventListener('abort',cancel);
|
|
92
|
+
body?.destroy();input?.destroy();
|
|
93
|
+
await Promise.allSettled([bodyDone,inputDone]);
|
|
94
|
+
await response?.body?.cancel().catch(()=>{});
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const effects=new WeakMap();
|
|
99
|
+
export const readPartTransferEffect=error=>error&&typeof error==='object'?effects.get(error):undefined;
|
|
100
|
+
export async function uploadGrantedPart(file,authorization,grant,options={}){
|
|
101
|
+
let dispatched=false;
|
|
102
|
+
try{return await transferGrantedPart(file,authorization,grant,{...options,fetch:async(...args)=>{
|
|
103
|
+
dispatched=true;return(options.fetch??globalThis.fetch)(...args);
|
|
104
|
+
}});}catch(error){
|
|
105
|
+
if(error&&typeof error==='object')effects.set(error,dispatched?'unknown':'not_dispatched');
|
|
106
|
+
throw error;
|
|
107
|
+
}
|
|
108
|
+
}
|