oneie 4.0.2 → 4.2.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.
@@ -0,0 +1,73 @@
1
+ /**
2
+ * The sealed envelope, as far as THIS module is concerned.
3
+ *
4
+ * Deliberately a local structural type rather than an import of
5
+ * `@oneie/sdk/vault-file`'s `VaultBlob`. Nothing here seals or opens anything —
6
+ * it moves an opaque JSON object on and off disk and reads exactly three fields
7
+ * of it. Importing the crypto module to borrow a type would drag Argon2id into
8
+ * the dependency graph of a file that never derives a key, and would couple the
9
+ * CLI's two-runtime-dep budget to a subpath that has to be linked before it
10
+ * resolves. The full type lives with the code that actually uses it.
11
+ */
12
+ export interface SealedVault {
13
+ v: 1;
14
+ wrap: 'passphrase' | 'keychain';
15
+ authPub?: string;
16
+ [k: string]: unknown;
17
+ }
18
+ export declare const VAULT_FILE_NAME = "wallet.json";
19
+ export interface VaultWriteResult {
20
+ ok: boolean;
21
+ path?: string;
22
+ error?: string;
23
+ }
24
+ /** Where a project's vault lives. */
25
+ export declare function vaultPath(dir: string): string;
26
+ /**
27
+ * Write the sealed vault. Ignore entry FIRST — same order, same reason as the
28
+ * API key: a secret written before it is ignored is exposed for the width of the
29
+ * gap, and the gap is where `git add -A` lives. Refuses rather than writing an
30
+ * unignorable credential.
31
+ */
32
+ export declare function writeVaultFolder(dir: string, blob: SealedVault): VaultWriteResult;
33
+ /** Read a sealed vault, or null when the folder has none. Never throws. */
34
+ export declare function readVaultFolder(dir: string): SealedVault | null;
35
+ /**
36
+ * The Keychain service name a vault's wrapping secret is stored under.
37
+ *
38
+ * Scoped by the vault's public identity rather than a constant, so two projects
39
+ * on one machine do not fight over one entry — and so deleting one wallet's
40
+ * secret cannot silently unlock another's.
41
+ */
42
+ export declare function keychainService(authPub: string): string;
43
+ export type KeychainResult = {
44
+ ok: true;
45
+ value?: string;
46
+ } | {
47
+ ok: false;
48
+ error: string;
49
+ };
50
+ /** macOS only — every other platform gets a clear refusal, never a silent no-op. */
51
+ export declare function keychainAvailable(): boolean;
52
+ /**
53
+ * Store the wrapping secret in Apple Keychain, gated by the user's login
54
+ * keychain ACL.
55
+ *
56
+ * `-w` takes the secret on argv, which is normally the thing to avoid — argv is
57
+ * world-readable in `ps`. It is accepted HERE because `security` offers no stdin
58
+ * form for add-generic-password, and the exposure is a race against a local
59
+ * process that could read the unlocked vault anyway. The mnemonic itself never
60
+ * appears on argv; only this random wrapper does, and it is useless without the
61
+ * file.
62
+ */
63
+ export declare function keychainStore(authPub: string, secret: string): KeychainResult;
64
+ /** Read the wrapping secret back. This is the call that prompts for Touch ID. */
65
+ export declare function keychainRead(authPub: string): KeychainResult;
66
+ /**
67
+ * The 24 words laid out for transcription, numbered.
68
+ *
69
+ * Numbered because BIP-39 order is load-bearing and an unnumbered column of 24
70
+ * words is trivially copied out of sequence — a wallet that restores to the
71
+ * wrong addresses with no error. Pure, so it is testable without a wallet.
72
+ */
73
+ export declare function paperSheet(mnemonic: string, addresses: Record<string, string>): string;
@@ -0,0 +1,184 @@
1
+ /**
2
+ * vaultfile.ts — the encrypted wallet folder, and the three ways out of it.
3
+ *
4
+ * `.one/wallet.json` is a sealed 24-word mnemonic. From it `recoverWallet()`
5
+ * derives all four chain keys offline, so the file IS the wallet: lose it and
6
+ * the phrase and the money is gone; copy it and the copy is equally the wallet.
7
+ * That is the property the three export paths below exist to serve.
8
+ *
9
+ * THE KEYS NEVER LEAVE THIS MACHINE unless the human deliberately moves them,
10
+ * and there are exactly three doors:
11
+ * · PAPER — the 24 words, printed once, offline forever.
12
+ * · KEYCHAIN — Apple Keychain (or any OS keystore) holds the WRAPPING secret,
13
+ * released by biometrics. The vault stays on disk.
14
+ * · ADDRESSES — public only. `wallet register` uploads these to be paid at;
15
+ * they are not key material and never were.
16
+ * Nothing else is an export. In particular nothing here ever posts a mnemonic,
17
+ * a private key, or a passphrase to a server — there is no code path for it.
18
+ *
19
+ * WHAT THE SECURE ENCLAVE ACTUALLY DOES, because the difference matters and is
20
+ * easy to oversell: the SE holds NIST P-256 keys ONLY. It cannot hold the
21
+ * ed25519 (Sui, Solana) or secp256k1 (EVM, BTC) keys this wallet is made of. So
22
+ * "open and close it with your biometrics" is TRUE — Touch ID releases the
23
+ * wrapping secret that decrypts the vault — while "your keys live in the Secure
24
+ * Enclave" is FALSE. Once unlocked, the chain keys are in this process's memory
25
+ * like any other program's. That is a real and useful boundary; it is not a
26
+ * hardware signer, and the code says so where a reader will meet it.
27
+ *
28
+ * The write ceremony is `keyfile.ts`'s, reused rather than re-derived: ignore
29
+ * entry before the file, 0700 directory, O_NOFOLLOW writes, symlink refusal.
30
+ * A second implementation of that is a second thing to get wrong.
31
+ */
32
+ import { existsSync, readFileSync, lstatSync } from 'node:fs';
33
+ import { join } from 'node:path';
34
+ import { spawnSync } from 'node:child_process';
35
+ import { ensureIgnored, KEY_DIR_NAME, LEGACY_KEY_DIR_NAME, writeSecret, canonicalDir } from './keyfile.js';
36
+ export const VAULT_FILE_NAME = 'wallet.json';
37
+ /** Where a project's vault lives. */
38
+ export function vaultPath(dir) {
39
+ const root = canonicalDir(dir);
40
+ const current = join(root, KEY_DIR_NAME, VAULT_FILE_NAME);
41
+ if (existsSync(current))
42
+ return current;
43
+ const legacy = join(root, LEGACY_KEY_DIR_NAME, VAULT_FILE_NAME);
44
+ // A vault minted before the rename still opens. New ones are always written
45
+ // to the current directory — vaultPath is used for BOTH, so the fallback only
46
+ // wins when a legacy file is actually there.
47
+ return existsSync(legacy) ? legacy : current;
48
+ }
49
+ /**
50
+ * Write the sealed vault. Ignore entry FIRST — same order, same reason as the
51
+ * API key: a secret written before it is ignored is exposed for the width of the
52
+ * gap, and the gap is where `git add -A` lives. Refuses rather than writing an
53
+ * unignorable credential.
54
+ */
55
+ export function writeVaultFolder(dir, blob) {
56
+ const root = canonicalDir(dir);
57
+ if (!existsSync(root))
58
+ return { ok: false, error: `no such directory: ${root}` };
59
+ if (!ensureIgnored(root)) {
60
+ return { ok: false, error: 'could not write .gitignore — refusing to write a wallet git can see' };
61
+ }
62
+ const path = vaultPath(root);
63
+ if (existsSync(path)) {
64
+ // Overwriting a vault destroys a wallet. There is no undo and no backup,
65
+ // so this refuses and makes the operator move the old one by hand.
66
+ return { ok: false, error: `${path} already exists — move it aside first; overwriting destroys the wallet it holds` };
67
+ }
68
+ try {
69
+ writeSecret(path, JSON.stringify(blob, null, 2) + '\n');
70
+ return { ok: true, path };
71
+ }
72
+ catch (err) {
73
+ return { ok: false, error: `write failed: ${err.message}` };
74
+ }
75
+ }
76
+ /** Read a sealed vault, or null when the folder has none. Never throws. */
77
+ export function readVaultFolder(dir) {
78
+ const path = vaultPath(dir);
79
+ if (!existsSync(path))
80
+ return null;
81
+ try {
82
+ // lstat, not stat: a symlinked vault is refused rather than followed to a
83
+ // file whose mode looks fine.
84
+ const st = lstatSync(path);
85
+ if (st.isSymbolicLink())
86
+ return null;
87
+ if ((st.mode & 0o077) !== 0)
88
+ return null;
89
+ const blob = JSON.parse(readFileSync(path, 'utf8'));
90
+ return blob?.v === 1 ? blob : null;
91
+ }
92
+ catch {
93
+ return null;
94
+ }
95
+ }
96
+ // ─── Keychain ────────────────────────────────────────────────────────────────
97
+ /**
98
+ * The Keychain service name a vault's wrapping secret is stored under.
99
+ *
100
+ * Scoped by the vault's public identity rather than a constant, so two projects
101
+ * on one machine do not fight over one entry — and so deleting one wallet's
102
+ * secret cannot silently unlock another's.
103
+ */
104
+ export function keychainService(authPub) {
105
+ return `one.ie.wallet.${authPub}`;
106
+ }
107
+ /** macOS only — every other platform gets a clear refusal, never a silent no-op. */
108
+ export function keychainAvailable() {
109
+ return process.platform === 'darwin' && spawnSync('which', ['security']).status === 0;
110
+ }
111
+ /**
112
+ * Store the wrapping secret in Apple Keychain, gated by the user's login
113
+ * keychain ACL.
114
+ *
115
+ * `-w` takes the secret on argv, which is normally the thing to avoid — argv is
116
+ * world-readable in `ps`. It is accepted HERE because `security` offers no stdin
117
+ * form for add-generic-password, and the exposure is a race against a local
118
+ * process that could read the unlocked vault anyway. The mnemonic itself never
119
+ * appears on argv; only this random wrapper does, and it is useless without the
120
+ * file.
121
+ */
122
+ export function keychainStore(authPub, secret) {
123
+ if (!keychainAvailable())
124
+ return { ok: false, error: 'Keychain is macOS-only' };
125
+ const r = spawnSync('security', [
126
+ 'add-generic-password',
127
+ '-a', process.env.USER ?? 'one',
128
+ '-s', keychainService(authPub),
129
+ '-w', secret,
130
+ '-U',
131
+ '-T', '', // no app is pre-trusted: every read prompts, which is the biometric gate
132
+ ]);
133
+ if (r.status !== 0) {
134
+ return { ok: false, error: (r.stderr?.toString() || 'security add-generic-password failed').trim() };
135
+ }
136
+ return { ok: true };
137
+ }
138
+ /** Read the wrapping secret back. This is the call that prompts for Touch ID. */
139
+ export function keychainRead(authPub) {
140
+ if (!keychainAvailable())
141
+ return { ok: false, error: 'Keychain is macOS-only' };
142
+ const r = spawnSync('security', [
143
+ 'find-generic-password',
144
+ '-a', process.env.USER ?? 'one',
145
+ '-s', keychainService(authPub),
146
+ '-w',
147
+ ]);
148
+ if (r.status !== 0) {
149
+ return { ok: false, error: 'no Keychain entry for this wallet (or access was denied)' };
150
+ }
151
+ return { ok: true, value: r.stdout.toString().trim() };
152
+ }
153
+ // ─── Paper ───────────────────────────────────────────────────────────────────
154
+ /**
155
+ * The 24 words laid out for transcription, numbered.
156
+ *
157
+ * Numbered because BIP-39 order is load-bearing and an unnumbered column of 24
158
+ * words is trivially copied out of sequence — a wallet that restores to the
159
+ * wrong addresses with no error. Pure, so it is testable without a wallet.
160
+ */
161
+ export function paperSheet(mnemonic, addresses) {
162
+ const words = mnemonic.trim().split(/\s+/);
163
+ const rows = [];
164
+ const half = Math.ceil(words.length / 2);
165
+ for (let i = 0; i < half; i++) {
166
+ const l = `${String(i + 1).padStart(2, ' ')}. ${(words[i] ?? '').padEnd(10)}`;
167
+ const j = i + half;
168
+ const r = j < words.length ? `${String(j + 1).padStart(2, ' ')}. ${words[j]}` : '';
169
+ rows.push(` ${l} ${r}`.trimEnd());
170
+ }
171
+ return [
172
+ 'ONE — wallet recovery sheet',
173
+ '',
174
+ 'These 24 words ARE the wallet. Anyone who reads them owns it.',
175
+ 'Write them down in this order. Store the paper offline.',
176
+ '',
177
+ ...rows,
178
+ '',
179
+ 'Receiving addresses (public — safe to share, this is how you get paid):',
180
+ ...Object.entries(addresses).map(([chain, addr]) => ` ${chain.padEnd(5)} ${addr}`),
181
+ '',
182
+ 'Restore with: one wallet open --recover',
183
+ ].join('\n');
184
+ }
@@ -0,0 +1,2 @@
1
+ import { Command } from 'commander';
2
+ export declare function mediaCmd(): Command;
@@ -0,0 +1,256 @@
1
+ import { Command } from 'commander';
2
+ import { readFileSync, statSync } from 'node:fs';
3
+ import { basename, extname } from 'node:path';
4
+ import { mediaListAllWith } from '@oneie/sdk';
5
+ import { authHeaders, jsonMode, resolveBase } from './lib/client.js';
6
+ import { askPath } from './lib/api-path.js';
7
+ // `one media` — the two media doors a JSON body cannot serve comfortably.
8
+ //
9
+ // WHAT IS DELIBERATELY NOT HERE, and why. The CLI already reaches every receiver:
10
+ // `one ask <receiver> --data '<json>'` (substrate.ts). So a subcommand has to earn
11
+ // its place the way `one tasks board` does — by doing work the raw ask cannot.
12
+ //
13
+ // list EARNS IT — media:list is ONE R2 scan per call with a budget and a
14
+ // cursor, and its `total` is per-page AND a floor whenever `truncated`
15
+ // is present. A raw ask prints scan one and READS AS COMPLETE. That is
16
+ // the 200-row-clamp defect, and it is what this renderer refuses to do.
17
+ // upload EARNS IT — media:upload takes `{ url | base64 }`. You cannot put a
18
+ // local file in a JSON body by hand. This reads it, sizes it against the
19
+ // door's own 5 MiB cap before spending a request, and encodes it.
20
+ // generate DECLINED — it is a prompt string in a JSON body. The answer is
21
+ // `one ask media:generate --data '{"prompt":"a red bicycle"}'`, which is
22
+ // not worse than a wrapper would be. Documented, not built.
23
+ //
24
+ // WORKSPACE. `--workspace` is offered on BOTH verbs because media:upload REFUSES a
25
+ // workspace you may not write ("A refusal is never a downgrade to your own
26
+ // workspace" — its own error describe()). That is the one thing that makes a write
27
+ // flag safe here: the older HTTP doors derive the slug from the session and ignore
28
+ // what they are handed, so an agency's upload landed in the agency's library and
29
+ // looked like it worked. This receiver does not, and the printed `key` proves it —
30
+ // it names the workspace prefix the bytes actually reached.
31
+ const DEFAULT_API = 'https://api.one.ie';
32
+ /** The door's own hard cap (media:upload: "5 MiB hard cap"). Checked here so a
33
+ * doomed 6.7 MiB base64 body is never sent — the refusal is instant and names the number. */
34
+ const UPLOAD_MAX_BYTES = 5 * 1024 * 1024;
35
+ /** media:list's `prefix` is an enum, not a free string — refuse locally rather than
36
+ * spend a request on a value the zod schema will reject. */
37
+ const PREFIXES = ['media', 'chat', 'ads', 'products', 'pages', 'brand', 'courses'];
38
+ const VIDEO_EXT = new Set(['.mp4', '.webm', '.mov', '.m4v', '.avi', '.mkv']);
39
+ const CONTENT_TYPES = {
40
+ '.png': 'image/png',
41
+ '.jpg': 'image/jpeg',
42
+ '.jpeg': 'image/jpeg',
43
+ '.gif': 'image/gif',
44
+ '.webp': 'image/webp',
45
+ '.avif': 'image/avif',
46
+ };
47
+ function fail(msg) {
48
+ process.stderr.write(`error ${msg}\n`);
49
+ process.exitCode = 1;
50
+ }
51
+ function asker(api) {
52
+ const base = resolveBase({ api }, DEFAULT_API);
53
+ return async (receiver, data, timeoutMs) => {
54
+ const res = await fetch(askPath(base, receiver), {
55
+ method: 'POST',
56
+ headers: authHeaders(),
57
+ body: JSON.stringify(timeoutMs ? { data, timeoutMs } : { data }),
58
+ });
59
+ const text = await res.text();
60
+ let body;
61
+ try {
62
+ body = text ? JSON.parse(text) : undefined;
63
+ }
64
+ catch {
65
+ throw new Error(`${receiver} → ${res.status} ${text.slice(0, 200)}`);
66
+ }
67
+ // A refusal wears an envelope at HTTP 200 as readily as at 4xx — read the envelope, not the status.
68
+ if (!res.ok && !(body && typeof body === 'object' && 'outcome' in body)) {
69
+ throw new Error(`${receiver} → ${res.status} ${text.slice(0, 200)}`);
70
+ }
71
+ return unwrap(receiver, body);
72
+ };
73
+ }
74
+ /** Unwrap the ask door's `{ outcome, result }`. A failure whose result is a receiver
75
+ * body (`{ ok:false, error }`) is RETURNED, not thrown — the caller keeps its receipt. */
76
+ function unwrap(receiver, raw) {
77
+ if (!raw || typeof raw !== 'object')
78
+ throw new Error(`${receiver}: empty response`);
79
+ const o = raw;
80
+ if ('outcome' in o) {
81
+ if (o.outcome === 'result')
82
+ return o.result ?? {};
83
+ const inner = o.result;
84
+ if (inner && typeof inner === 'object' && ('ok' in inner || 'error' in inner)) {
85
+ return { ok: false, ...inner, error: inner.error ?? String(o.outcome) };
86
+ }
87
+ const why = typeof o.reason === 'string' ? ` (${o.reason})` : '';
88
+ throw new Error(`${receiver}: ${String(o.outcome)}${why}`);
89
+ }
90
+ if ('result' in o)
91
+ return o.result ?? {};
92
+ return o;
93
+ }
94
+ function human(bytes) {
95
+ if (bytes === null || bytes === undefined)
96
+ return '?';
97
+ if (bytes < 1024)
98
+ return `${bytes}B`;
99
+ if (bytes < 1024 * 1024)
100
+ return `${(bytes / 1024).toFixed(1)}K`;
101
+ return `${(bytes / 1024 / 1024).toFixed(1)}M`;
102
+ }
103
+ function counts(rec) {
104
+ const rows = Object.entries(rec ?? {}).sort((a, b) => b[1] - a[1]);
105
+ return rows.length ? rows.map(([k, v]) => `${k || '(root)'}=${v}`).join(' ') : '-';
106
+ }
107
+ function renderList(res) {
108
+ const items = res.items ?? [];
109
+ const w = process.stdout;
110
+ // ABSENT IS NOT FALSE: a complete answer carries no `truncated` key at all.
111
+ const short = res.truncated !== undefined;
112
+ // THE RULE: a total beside a present `truncated` is a FLOOR, never a count.
113
+ const totalTxt = res.total === undefined ? '?' : short ? `at least ${res.total}` : `${res.total}`;
114
+ w.write(`${items.length} rows, ${totalTxt} media` +
115
+ `${res.scanned !== undefined ? ` scanned=${res.scanned} objects` : ''}` +
116
+ `${res.pages ? ` pages=${res.pages}` : ''}\n`);
117
+ if (short) {
118
+ w.write(`TRUNCATED: the scan budget bit — "${res.total ?? '?'}" is a FLOOR, not a count ` +
119
+ `${JSON.stringify(res.truncated)}\n`);
120
+ }
121
+ if (res.nextCursor) {
122
+ w.write(`MORE: nextCursor=${res.nextCursor} — rerun with --all to walk every page\n`);
123
+ }
124
+ // scanned far above total means most of the bucket is not media — following the
125
+ // cursor is the right move, and concluding "empty workspace" is the wrong one.
126
+ if (!short && res.scanned !== undefined && res.total !== undefined && res.scanned > res.total * 4) {
127
+ w.write(`note most of what was scanned is not media (${res.total} of ${res.scanned})\n`);
128
+ }
129
+ if (res.byPrefix)
130
+ w.write(`byPrefix ${counts(res.byPrefix)}\n`);
131
+ if (items.length)
132
+ w.write('\n');
133
+ for (const it of items) {
134
+ w.write(`${it.key} ${it.kind} ${human(it.size)} ${it.contentType} ${it.uploaded ?? '-'}\n`);
135
+ }
136
+ }
137
+ export function mediaCmd() {
138
+ const cmd = new Command('media').description('A workspace media library — list the WHOLE of it, upload a local file. ' +
139
+ '(generate has no subcommand on purpose: one ask media:generate --data \'{"prompt":"..."}\')');
140
+ cmd
141
+ .command('list')
142
+ .description('List media (media:list) — rows, an honest total, and a loud word when the scan was cut short')
143
+ .option('--workspace <slug>', 'Group slug to read (default: your own). Honoured only if you may read it.')
144
+ .option('--kind <k>', 'image | video — filters the rows on a page, does not change what is scanned')
145
+ .option('--prefix <p>', `Only this namespace: ${PREFIXES.join(' | ')}`)
146
+ .option('--limit <n>', 'R2 objects to SCAN per page BEFORE filtering — not a row count. Default 500, max 1000.')
147
+ .option('--all', 'Follow nextCursor until every page is read (ceiling 20 pages)')
148
+ .option('--api <url>', 'API base URL', DEFAULT_API)
149
+ .option('--json', 'Print the raw response')
150
+ .action(async (opts, sub) => {
151
+ if (opts.kind && opts.kind !== 'image' && opts.kind !== 'video') {
152
+ return fail("--kind must be 'image' or 'video'");
153
+ }
154
+ if (opts.prefix && !PREFIXES.includes(opts.prefix)) {
155
+ return fail(`--prefix must be one of: ${PREFIXES.join(', ')}`);
156
+ }
157
+ const limit = opts.limit === undefined ? undefined : Number(opts.limit);
158
+ if (limit !== undefined && (!Number.isInteger(limit) || limit < 1 || limit > 1000)) {
159
+ return fail('--limit must be a whole number from 1 to 1000 (R2\'s own ceiling)');
160
+ }
161
+ const req = {
162
+ ...(opts.workspace ? { workspace: opts.workspace } : {}),
163
+ ...(opts.kind ? { kind: opts.kind } : {}),
164
+ ...(opts.prefix ? { prefix: opts.prefix } : {}),
165
+ ...(limit !== undefined ? { limit } : {}),
166
+ };
167
+ const ask = asker(opts.api);
168
+ let res;
169
+ try {
170
+ res = opts.all
171
+ ? await mediaListAllWith((r, d) => ask(r, d), req)
172
+ : (await ask('media:list', req));
173
+ }
174
+ catch (e) {
175
+ return fail(e instanceof Error ? e.message : String(e));
176
+ }
177
+ if (jsonMode(sub))
178
+ process.stdout.write(JSON.stringify(res, null, 2) + '\n');
179
+ else if (res.ok !== false)
180
+ renderList(res);
181
+ if (res.ok === false)
182
+ fail(res.error ?? 'media:list failed');
183
+ });
184
+ cmd
185
+ .command('upload <path>')
186
+ .description('Upload a LOCAL image file (media:upload) — read, sized against the 5 MiB cap, base64 encoded. ' +
187
+ 'For a remote URL: one ask media:upload --data \'{"url":"https://…"}\'')
188
+ .option('--workspace <slug>', 'Group slug to write (default: your own). A workspace you may not write is REFUSED, never downgraded.')
189
+ .option('--content-type <ct>', 'A HINT only — the stored type is decided by the magic bytes')
190
+ .option('--filename <name>', 'A LABEL for the key, not a path (default: the basename). The extension always comes from the sniffed bytes.')
191
+ .option('--api <url>', 'API base URL', DEFAULT_API)
192
+ .option('--json', 'Print the raw response')
193
+ .action(async (path, opts, sub) => {
194
+ let size;
195
+ try {
196
+ const st = statSync(path);
197
+ if (!st.isFile())
198
+ return fail(`${path} is not a file`);
199
+ size = st.size;
200
+ }
201
+ catch (e) {
202
+ return fail(`${path}: ${e instanceof Error ? e.message : String(e)}`);
203
+ }
204
+ if (size === 0)
205
+ return fail(`${path} is empty`);
206
+ const ext = extname(path).toLowerCase();
207
+ if (VIDEO_EXT.has(ext)) {
208
+ // Not a policy this CLI invented — media:upload declares "video is not
209
+ // accepted here" and names the door that does. Refusing locally spends no
210
+ // request and points at the right one.
211
+ return fail(`${path} is video, and media:upload takes raster images only. Nothing was sent. ` +
212
+ 'There is no receiver for video yet — the streamed door is PUT /api/media/video-upload (100 MB).');
213
+ }
214
+ if (ext === '.svg') {
215
+ return fail(`${path} is SVG, which media:upload refuses deliberately (the public reader serves the stored type verbatim). Nothing was sent.`);
216
+ }
217
+ if (size > UPLOAD_MAX_BYTES) {
218
+ return fail(`${path} is ${human(size)} — media:upload caps at ${human(UPLOAD_MAX_BYTES)}. Nothing was sent. ` +
219
+ 'Host the file and pass a URL instead: one ask media:upload --data \'{"url":"https://…"}\'');
220
+ }
221
+ const contentType = opts.contentType ?? CONTENT_TYPES[ext];
222
+ let base64;
223
+ try {
224
+ base64 = readFileSync(path).toString('base64');
225
+ }
226
+ catch (e) {
227
+ return fail(`${path}: ${e instanceof Error ? e.message : String(e)}`);
228
+ }
229
+ const data = {
230
+ base64,
231
+ filename: opts.filename ?? basename(path, ext),
232
+ ...(opts.workspace ? { workspace: opts.workspace } : {}),
233
+ ...(contentType ? { contentType } : {}),
234
+ };
235
+ let res;
236
+ try {
237
+ // 30s is the ask door's own ceiling, and a 5 MiB body measured 6.6s wall to prod.
238
+ res = (await asker(opts.api)('media:upload', data, 30_000));
239
+ }
240
+ catch (e) {
241
+ return fail(e instanceof Error ? e.message : String(e));
242
+ }
243
+ if (jsonMode(sub)) {
244
+ process.stdout.write(JSON.stringify(res, null, 2) + '\n');
245
+ }
246
+ else if (res.ok !== false) {
247
+ // The `key` is the receipt: it names the workspace prefix the bytes ACTUALLY
248
+ // reached. Printed always, so a --workspace upload can never merely look right.
249
+ process.stdout.write(`ok key=${res.key ?? '?'} kind=${res.kind ?? '?'} type=${res.contentType ?? '?'} stored=${human(res.size)} sent=${human(size)}\n` +
250
+ ` ${res.url ?? ''}\n`);
251
+ }
252
+ if (res.ok === false)
253
+ fail(res.error ?? 'media:upload failed');
254
+ });
255
+ return cmd;
256
+ }
@@ -19,8 +19,17 @@ function apiBase(opts) {
19
19
  return resolveBase(opts, 'https://one.ie');
20
20
  }
21
21
  function bearerHeaders(workspace) {
22
+ // THE TOKEN IS THE PLAIN KEY -- the eleventh site of the `${slug}:${key}` bug.
23
+ // `requireAuth` (one.ie/web/src/lib/api-auth.ts:317) resolves a world key by
24
+ // PREFIX (`one-` / `osk_`), so prepending "<workspace>:" produces
25
+ // `one:one-abc...`, which matches no prefix, falls through to session auth and
26
+ // 401s. Ten call sites in agent.ts and skill.ts were fixed for exactly this;
27
+ // this one was missed, which broke `plugin buy` (POST /api/ask/plugins:buy,
28
+ // gated by requireAuth) and `plugin source` for every key-authenticated user.
29
+ // The workspace still gates whether we send auth at all -- it just never
30
+ // belonged inside the credential.
22
31
  const key = resolveKey();
23
- return key && workspace ? { Authorization: `Bearer ${workspace}:${key}` } : {};
32
+ return key && workspace ? { Authorization: `Bearer ${key}` } : {};
24
33
  }
25
34
  // npm pack wraps a package's contents under a "package/" root — strip-components=1 lands
26
35
  // the real package.json + src/ directly at ./plugin-<name>/, same as a real npm install would.