@@ -39,7 +39,7 @@ import { Log } from "@/altimate/util/log"
3939import { Global } from "@/global"
4040import { Filesystem } from "@/util/filesystem"
4141import { AltimateApi } from "@/altimate/api/client"
42- import { ConflictError , ForbiddenError , NotFoundError , altimateRequest } from "./api-client"
42+ import { ConflictError , ForbiddenError , NotFoundError , WorkspaceApi , altimateRequest } from "./api-client"
4343import { resolveBinding } from "./state"
4444
4545const log = Log . create ( { service : "altimate-workspace-skill-publish" } )
@@ -51,19 +51,25 @@ const SKILLS_BASE = "/skills"
5151const MANAGED_DIR = path . join ( ".altimate-code" , "skill" , "_workspace" )
5252
5353/** Mirrors the server's own ceilings so an oversized bundle fails locally, with a
54- * usable message, instead of after a long upload. */
54+ * usable message, instead of after a long upload. `MAX_BUNDLE_FILES` and
55+ * `MAX_BUNDLE_BYTES` in `app/service/custom_skills/bundle.py`; a mismatch
56+ * here means a bundle that passes locally, uploads in full, and is refused
57+ * with a 400 — which is the case these exist to prevent. */
5558const MAX_BUNDLE_BYTES = 10 * 1024 * 1024
56- const MAX_BUNDLE_FILES = 200
59+ const MAX_BUNDLE_FILES = 100
5760
5861/** Never published, whatever is in the directory.
5962 *
6063 * A skill directory is a folder the user works in, so it accumulates things
6164 * that are not the skill: an editor's swap file, macOS's `.DS_Store`, a `.git`
62- * from a skill installed by clone — and `.env`, which is the one that matters.
63- * Publishing is a share: a public skill's bundle is readable tenant-wide, and
64- * a secret that reaches it cannot be recalled by deleting the file locally.
65- * Skipped silently, where a named refusal would be noise about files the user
66- * did not mean to publish either. */
65+ * from a skill installed by clone — and `.env` / `.envrc`, which are the ones
66+ * that matter. Publishing is a share: a public skill's bundle is readable
67+ * tenant-wide, and a secret that reaches it cannot be recalled by deleting the
68+ * local file. Skipped silently, where a named refusal would be noise about
69+ * files the user did not mean to publish either.
70+ *
71+ * A blocklist, so incomplete by construction: it catches the common shapes,
72+ * not every file that could hold a secret. A `credentials.json` ships. */
6773const NEVER_PUBLISH_DIRS = new Set ( [ ".git" , "node_modules" , "__pycache__" ] )
6874function isJunkFile ( name : string ) : boolean {
6975 // Case-folded: Windows and macOS file systems are case-insensitive by
@@ -77,6 +83,7 @@ function isJunkFile(name: string): boolean {
7783 lower === ".ds_store" ||
7884 lower === "thumbs.db" ||
7985 lower === ".env" ||
86+ lower === ".envrc" ||
8087 lower . startsWith ( ".env." ) ||
8188 lower . endsWith ( "~" ) ||
8289 lower . endsWith ( ".swp" ) ||
@@ -162,6 +169,24 @@ export class NotLinkedError extends Error {
162169 }
163170}
164171
172+ /** The project is linked to a workspace the caller does not own. Linking
173+ * needs only visibility — a colleague's shared workspace can be linked to —
174+ * but attaching a skill is a write against the workspace and needs
175+ * ownership. Raised BEFORE anything is uploaded, for the same reason as
176+ * `NotLinkedError`: a skill created and then refused attachment is the
177+ * orphan this module exists to prevent, and nothing from the CLI would ever
178+ * attach it. */
179+ export class NotWorkspaceOwnerError extends Error {
180+ constructor ( readonly workspaceName : string ) {
181+ super (
182+ `This project is linked to "${ workspaceName } ", which belongs to someone else. ` +
183+ `Skills can only be published to a workspace you own — link this project to one of yours, ` +
184+ `or ask the owner to publish it.` ,
185+ )
186+ this . name = "NotWorkspaceOwnerError"
187+ }
188+ }
189+
165190/** The skill exists on the server but could not be attached to the workspace.
166191 * Carries the id so the caller can say so precisely: the next publish takes the
167192 * update path and retries the attachment, so nothing is stranded. */
@@ -324,19 +349,27 @@ interface PublishedRecord {
324349 publicId : string
325350 tenant : string
326351 apiUrl : string
352+ /** The server's `created_by` for the skill. Present on rows written by
353+ * this version; absent on legacy rows, which are re-homed on first read. */
354+ createdBy ?: number
327355}
328356
329357function ledgerPath ( ) : string {
330358 return path . join ( Global . Path . state , "altimate-published-skills.json" )
331359}
332360
361+ /** Test seam: where the ledger lives, so a test can seed a legacy row without
362+ * guessing the state directory. */
363+ export const ledgerPathForTests = ledgerPath
364+
333365/** Shape check, not a cast. The file comes off disk and could be anything — an
334366 * older layout, hand-edited, half-written. A malformed row must be dropped rather
335367 * than trusted into a PATCH against a garbage id. */
336368function isPublishedRecord ( value : unknown ) : value is PublishedRecord {
337369 if ( ! value || typeof value !== "object" ) return false
338370 const r = value as Record < string , unknown >
339- return typeof r . publicId === "string" && typeof r . tenant === "string" && typeof r . apiUrl === "string"
371+ if ( typeof r . publicId !== "string" || typeof r . tenant !== "string" || typeof r . apiUrl !== "string" ) return false
372+ return r . createdBy === undefined || typeof r . createdBy === "number"
340373}
341374
342375async function readLedger ( ) : Promise < Record < string , PublishedRecord > > {
@@ -357,26 +390,38 @@ async function readLedger(): Promise<Record<string, PublishedRecord>> {
357390 }
358391}
359392
360- /** The account a publish runs under, as the ledger scopes it. The key
361- * fingerprint is in it because the server scopes skill names per CREATOR:
362- * two users of one tenant who publish the same directory are two creators,
363- * and a ledger keyed on tenant alone handed the second user the first user's
364- * id — a PATCH the server refuses with 403. A digest, never the key itself:
365- * the ledger is a plain file. */
393+ /** The account a publish runs under, as the ledger scopes it. The USER is in
394+ * it because the server scopes skill names per creator: two users of one
395+ * tenant who publish the same directory are two creators, and a ledger keyed
396+ * on tenant alone handed the second user the first user's id — a PATCH the
397+ * server refuses with 403.
398+ *
399+ * The user id, not a digest of the API key, which is what an earlier version
400+ * used. A key is rotated; the user is not. Under the digest a rotation made
401+ * every published id on this machine unreachable — the next publish created
402+ * again, the server answered 409 on the name, and the user was told the
403+ * skill "was published from somewhere else". */
366404interface LedgerScope {
367405 tenant : string
368406 apiUrl : string
369- keyDigest : string
407+ userId : number
370408}
371409
410+ /** Kept only to read rows written under the digest scheme. */
372411function keyDigest ( apiKey : string ) : string {
373412 return createHash ( "sha256" ) . update ( apiKey ) . digest ( "hex" ) . slice ( 0 , 16 )
374413}
375414
376- async function currentScope ( ) : Promise < LedgerScope | null > {
415+ async function currentScope ( ) : Promise < ( LedgerScope & { keyDigest : string } ) | null > {
377416 const creds = await AltimateApi . getCredentials ( ) . catch ( ( ) => null )
378417 if ( ! creds ) return null
379- return { tenant : creds . altimateInstanceName , apiUrl : creds . altimateUrl , keyDigest : keyDigest ( creds . altimateApiKey ) }
418+ const userId = await WorkspaceApi . whoami ( )
419+ return {
420+ tenant : creds . altimateInstanceName ,
421+ apiUrl : creds . altimateUrl ,
422+ userId,
423+ keyDigest : keyDigest ( creds . altimateApiKey ) ,
424+ }
380425}
381426
382427/** The skill directory as the ledger identifies it: its real path. `path.resolve`
@@ -401,7 +446,7 @@ function skillIdentity(skillDir: string): string {
401446 * previous account's id: switching back created a second skill and then 409'd on
402447 * the name that was already there, with no way to reach the original. */
403448function ledgerKey ( skillDir : string , scope : LedgerScope ) : string {
404- return `${ scope . tenant } |${ scope . apiUrl } |${ scope . keyDigest } |${ skillIdentity ( skillDir ) } `
449+ return `${ scope . tenant } |${ scope . apiUrl } |u ${ scope . userId } |${ skillIdentity ( skillDir ) } `
405450}
406451
407452/** Serialises ledger access, the same way `memory-index` serialises its own.
@@ -439,22 +484,53 @@ async function recordPublished(skillDir: string, scope: LedgerScope, record: Pub
439484 } )
440485}
441486
442- async function knownPublicId ( skillDir : string , scope : LedgerScope ) : Promise < string | null > {
443- return withLedger ( async ( ) => {
487+ async function knownPublicId (
488+ skillDir : string ,
489+ scope : LedgerScope & { keyDigest : string } ,
490+ ) : Promise < string | null > {
491+ const record = await withLedger ( async ( ) => {
444492 const ledger = await readLedger ( )
445- // Composite key first; fall back to the pre-fingerprint composite key and
446- // then to the directory -only key, so ids written by earlier versions are
447- // not stranded into a needless re-create.
448- const record =
493+ // Current key first, then the shapes earlier versions wrote — the
494+ // key-digest scope, the tenant -only scope, the bare directory — so ids
495+ // are not stranded into a needless re-create by an upgrade .
496+ return (
449497 ledger [ ledgerKey ( skillDir , scope ) ] ??
498+ ledger [ `${ scope . tenant } |${ scope . apiUrl } |${ scope . keyDigest } |${ skillIdentity ( skillDir ) } ` ] ??
450499 ledger [ `${ scope . tenant } |${ scope . apiUrl } |${ path . resolve ( skillDir ) } ` ] ??
451- ledger [ path . resolve ( skillDir ) ]
452- if ( ! record ) return null
453- // Still checked, not implied by the key: the fallback lookups above can
454- // return a legacy row belonging to another account.
455- if ( record . tenant !== scope . tenant || record . apiUrl !== scope . apiUrl ) return null
456- return record . publicId
500+ ledger [ path . resolve ( skillDir ) ] ??
501+ null
502+ )
457503 } )
504+ if ( ! record ) return null
505+ // Still checked, not implied by the key: a legacy row can belong to
506+ // another account.
507+ if ( record . tenant !== scope . tenant || record . apiUrl !== scope . apiUrl ) return null
508+ // A legacy row carries no creator. It is trusted only once the server says
509+ // the skill is this user's — one GET, and the row is re-homed under the
510+ // current key so the question is not asked again. Someone else's, or
511+ // gone: not ours, and the create path takes over.
512+ if ( record . createdBy === undefined ) {
513+ const owner = await skillOwner ( record . publicId )
514+ if ( owner !== scope . userId ) return null
515+ await recordPublished ( skillDir , scope , { ...record , createdBy : owner } )
516+ } else if ( record . createdBy !== scope . userId ) return null
517+ return record . publicId
518+ }
519+
520+ /** `created_by` from the skill's detail, or null when the skill is gone. */
521+ async function skillOwner ( publicId : string ) : Promise < number | null > {
522+ try {
523+ const detail = await altimateRequest < { created_by ?: unknown ; skill ?: { created_by ?: unknown } } > (
524+ "GET" ,
525+ `/${ encodeURIComponent ( publicId ) } ` ,
526+ { base : SKILLS_BASE } ,
527+ )
528+ const raw = detail ?. skill ?. created_by ?? detail ?. created_by
529+ return typeof raw === "number" ? raw : null
530+ } catch ( err ) {
531+ if ( err instanceof NotFoundError ) return null
532+ throw err
533+ }
458534}
459535
460536/** One publish per skill directory at a time. The ledger chain serialises the
@@ -533,16 +609,23 @@ async function publishSkillUnlocked(input: {
533609 const binding = await resolveBinding ( input . projectDirectory )
534610 if ( ! binding ) throw new NotLinkedError ( )
535611
536- const files = await collectBundle ( input . skillDirectory )
537- if ( files . length === 0 ) throw new EmptyBundleError ( )
538- const bytes = files . reduce ( ( n , f ) => n + Buffer . byteLength ( f . content , "utf8" ) , 0 )
539-
540612 // Resolved once and pinned. The ledger lookup and the record after the
541613 // upload must describe the same account, or a credential change mid-publish
542614 // files the id under one and looks for it under the other.
543615 const scope = await currentScope ( )
544616 if ( ! scope ) throw new NotLinkedError ( )
545617
618+ // And the workspace must be the caller's. Linking needs only visibility, so
619+ // a project can be bound to a colleague's shared workspace — where the
620+ // attach would answer 404, on every publish, leaving a skill nothing from
621+ // the CLI could ever attach. Same rule as the link check: nothing is
622+ // uploaded until the attach is known to be possible.
623+ await assertOwnsWorkspace ( binding . datamateId , binding . datamateName , scope . userId )
624+
625+ const files = await collectBundle ( input . skillDirectory )
626+ if ( files . length === 0 ) throw new EmptyBundleError ( )
627+ const bytes = files . reduce ( ( n , f ) => n + Buffer . byteLength ( f . content , "utf8" ) , 0 )
628+
546629 const existing = await knownPublicId ( input . skillDirectory , scope )
547630 if ( existing ) {
548631 try {
@@ -617,13 +700,30 @@ async function publishSkillUnlocked(input: {
617700 const publicId = extractPublicId ( created )
618701 if ( ! publicId ) throw new Error ( "The workspace accepted the skill but did not return an id for it." )
619702
620- await recordPublished ( input . skillDirectory , scope , { publicId, tenant : scope . tenant , apiUrl : scope . apiUrl } )
703+ await recordPublished ( input . skillDirectory , scope , {
704+ publicId,
705+ tenant : scope . tenant ,
706+ apiUrl : scope . apiUrl ,
707+ createdBy : extractCreatedBy ( created ) ?? scope . userId ,
708+ } )
621709 // After the id is recorded, deliberately. If the attach fails, the next
622710 // publish finds the id, takes the update path, and attaches again — rather
623711 // than creating a second copy and 409ing on the name.
624712 try {
625713 await attachToWorkspace ( publicId , binding . datamateId )
626714 } catch ( err ) {
715+ // A 404 straight after a create means the workspace refused the
716+ // attachment outright — not owned, or gone — and retrying will not change
717+ // that. The skill just created would be an orphan; take it back so
718+ // nothing is left behind, and say why.
719+ if ( err instanceof NotFoundError ) {
720+ await altimateRequest < unknown > ( "DELETE" , `/${ encodeURIComponent ( publicId ) } ` , {
721+ base : SKILLS_BASE ,
722+ allowEmptyBody : true ,
723+ } ) . catch ( ( cleanup ) => log . warn ( "could not remove an unattachable skill" , { publicId, err : String ( cleanup ) } ) )
724+ await forgetPublished ( input . skillDirectory , scope )
725+ throw new NotWorkspaceOwnerError ( binding . datamateName )
726+ }
627727 throw new AttachFailedError ( publicId , err )
628728 }
629729 return { action : "created" , publicId, name : input . name , files : files . length , bytes, datamateId : binding . datamateId }
@@ -640,6 +740,36 @@ function updateConflict(err: ConflictError, skillName: string): Error {
640740 return err
641741}
642742
743+ /** Refuse before upload when the bound workspace is not the caller's. Read
744+ * from the same list the picker uses, which carries each workspace's owner. A
745+ * list that omits the owner (an older server) cannot answer, and the attach
746+ * itself then decides — with the compensation on the create path. */
747+ async function assertOwnsWorkspace ( datamateId : number , datamateName : string , userId : number ) : Promise < void > {
748+ const workspaces = await WorkspaceApi . listDatamates ( )
749+ const ws = workspaces . find ( ( w ) => w . id === datamateId )
750+ if ( ws ?. ownerId !== undefined && ws . ownerId !== userId ) throw new NotWorkspaceOwnerError ( datamateName )
751+ }
752+
753+ function extractCreatedBy ( payload : unknown ) : number | null {
754+ if ( ! payload || typeof payload !== "object" ) return null
755+ const direct = ( payload as { created_by ?: unknown } ) . created_by
756+ if ( typeof direct === "number" ) return direct
757+ const nested = ( payload as { skill ?: { created_by ?: unknown } } ) . skill ?. created_by
758+ return typeof nested === "number" ? nested : null
759+ }
760+
761+ async function forgetPublished ( skillDir : string , scope : LedgerScope ) : Promise < void > {
762+ return withLedger ( async ( ) => {
763+ try {
764+ const ledger = await readLedger ( )
765+ delete ledger [ ledgerKey ( skillDir , scope ) ]
766+ Filesystem . writeJsonAtomic ( ledgerPath ( ) , ledger )
767+ } catch ( err ) {
768+ log . warn ( "could not forget an unattachable skill's id" , { err : String ( err ) } )
769+ }
770+ } )
771+ }
772+
643773/** Accepts the documented `{public_id}` and a `{skill: {public_id}}` envelope, so
644774 * a compat wrapper on either side does not strand the id — the same tolerance
645775 * `skill-sync` applies to the list and detail shapes. */
0 commit comments