Spaces:
Running

Millie / scripts /deploy-huggingface.js
AhmedMSLTI's picture
Add session-protected inventory test mode; retain public fictional Maya
2de6485 verified
Raw History Blame Contribute Delete
5.82 kB
import { readdir, readFile } from 'node:fs/promises';
import { outboundFetch } from '../server/network.js';
import { decryptInventory } from '../server/inventory-bundle.js';
// Explicit allowlist: .env, Git internals, credentials and build artifacts are
// never uploaded. Dependencies and frontend are built inside the Space.
const root = new URL('../', import.meta.url);
const files = ['README.md', 'Dockerfile', '.dockerignore', '.env.example', '.gitignore', '.npmrc', 'package.json', 'package-lock.json', 'index.html', 'config/vocalbridge-agent.json', 'config/vocalbridge-role.json', 'config/vocalbridge-inventory-role.json', 'config/vocalbridge-shared-role.json', 'data/synthetic.json'];
if (process.argv.includes('--with-protected-inventory')) {
const bundle = JSON.parse(await readFile(new URL('data/inventory.enc.json', root), 'utf8'));
const secrets = JSON.parse(await readFile(new URL('artifacts/test-access-secrets.json', root), 'utf8'));
decryptInventory(bundle, secrets.MAYA_INVENTORY_KEY); // authentication + full schema check before upload
files.push('data/inventory.enc.json');
}
async function collect(dir) {
for (const entry of await readdir(new URL(dir, root), { withFileTypes: true })) {
const path = `${dir}/${entry.name}`;
if (entry.isDirectory()) await collect(path);
else if (entry.isFile() && /\.(js|css|md)$/.test(entry.name)) files.push(path);
}
}
await collect('src');
await collect('server');
await collect('scripts');
await collect('tests');
await collect('docs');
const operations = [{ key: 'header', value: { summary: process.argv.includes('--with-protected-inventory') ? 'Add session-protected inventory test mode; retain public fictional Maya' : 'Deploy fictional Maya car voice demo' } }];
for (const path of files.sort()) {
const content = await readFile(new URL(path, root));
// Fail before network mutation if an uploaded source file appears to contain
// a live provider credential. Variable names and blank examples are allowed.
const text = content.toString('utf8');
if (/(?:hf_[A-Za-z0-9_-]{20,}|sk-(?:proj-)?[A-Za-z0-9_-]{20,})/.test(text)) throw new Error(`Possible credential in deployment file: ${path}`);
operations.push({ key: 'file', value: { path, encoding: 'base64', content: content.toString('base64') } });
}
if (process.argv.includes('--dry-run')) {
console.log(`Deployment bundle: ${files.length} files; blank .env.example only, no credentials.`);
console.log(files.join('\n'));
process.exit(0);
}
const token = process.env.HF_TOKEN;
if (!token) {
console.error('HF_TOKEN is missing. Supply a Hugging Face write token securely through environment settings.');
process.exit(1);
}
async function request(path, init = {}) {
return outboundFetch(`https://huggingface.co${path}`, {
...init, signal: AbortSignal.timeout(60000),
headers: { Authorization: `Bearer ${token}`, ...init.headers }
});
}
async function checked(path, init) {
const res = await request(path, init);
if (path === '/api/repos/create' && res.status === 402) {
throw new Error('Hugging Face requires a qualifying paid plan to create this Docker Space (HTTP 402). No plan or hardware upgrade was purchased.');
}
// Never log provider bodies or headers: authentication responses can contain
// sensitive account metadata. Status and operation are sufficient here.
if (!res.ok) throw new Error(`Hugging Face ${init?.method || 'GET'} ${path} failed (HTTP ${res.status}).`);
return res.json();
}
try {
const account = await checked('/api/whoami-v2');
const id = process.env.HF_SPACE_ID || `${account.name}/diva-car-demo`;
let visibility = 'private';
if (!/^[\w-]+\/[\w.-]+$/.test(id)) throw new Error('HF_SPACE_ID must be username/space-name.');
const [namespace, name] = id.split('/');
const existing = await request(`/api/spaces/${id}`);
if (existing.ok) {
const info = await existing.json();
if (process.env.HF_EXPECTED_COMMIT && info.sha !== process.env.HF_EXPECTED_COMMIT) throw new Error('Space changed after preflight. Refusing to overwrite an unreviewed revision.');
visibility = info.private ? 'private' : 'public';
const updatePrivate = process.argv.includes('--update');
const updatePublic = process.argv.includes('--update-public');
if (!updatePrivate && !updatePublic) throw new Error('Space already exists. Review it before explicitly deploying again with --update or --update-public.');
if (info.sdk !== 'docker') throw new Error('Updates require a Docker Space.');
if (info.private && !updatePrivate) throw new Error('Private Space updates require --update.');
if (!info.private && !updatePublic) throw new Error('Public Space updates require the explicit --update-public flag.');
if (info.sha) operations[0].value.parentCommit = info.sha;
} else if (existing.status === 404) {
await checked('/api/repos/create', {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ type: 'space', name, organization: namespace, private: true, sdk: 'docker' })
});
} else throw new Error(`Cannot inspect target Space (HTTP ${existing.status}).`);
await checked(`/api/spaces/${id}/commit/main`, {
method: 'POST', headers: { 'Content-Type': 'application/x-ndjson' },
body: `${operations.map(op => JSON.stringify(op)).join('\n')}\n`
});
console.log(`Uploaded ${visibility} Docker Space: https://huggingface.co/spaces/${id}`);
console.log('Add VOCAL_BRIDGE_API_KEY in Space Settings → Secrets. Optional: DEALERSHIP_OPENAI_API_KEY.');
console.log(visibility === 'public' ? 'Wait for the build, then open the Space on your phone.' : 'Wait for the build, then open the Space on your phone while signed into Hugging Face.');
} catch (error) {
console.error(error.message);
process.exitCode = 1;
}