Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

address review (claude): anchor TikTok host regex, validate reference scheme server-side, unassign orphaned recording layers on refresh

[._.]/ Adam Eivy82bc766b300a
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index a0e8e3be14..03472eea2b 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -88,7 +88,7 @@ grep -i "what you want to do" client/src/lib/README.md
|---|---|
| `cityPlaybackFrame.js` | Map a recorded CyberCity snapshot frame onto the prop shape CityScene/CityHud consume for the timeline scrubber (`mergeFrameIntoCityProps`, `buildPlaybackApps`, `buildPlaybackAgentMap`, `isPlayableFrame`). Honors `schemaVersion` and the capture-side null sentinels; returns only snapshot-backed props so unfed landmarks stay live. |
| `universeBuilderExpand.js` | `mergeExpandIntoDraft(draft, result)` — pure merge of a Universe Builder draft with the LLM expand-API response (lock honoring, category/sheet merge with `kind` precedence, canon dedupe by name/slugline/alias). Also exports `mergeVariations`, `mergeCanonByName`, and `extractPreservedFromDraft` for callers that need the building blocks (per-category Generate, save-time refetch+merge). |
-| `songCraft.js` | Canonical a cappella song-craft reference data rendered by the Songs Guide (`/songs/guide`) and reused by the Song editor: `RHYTHM_SHAPES` / `DIRGE_RHYTHM_SHAPES` (dirge & ballad pulse feels with BPM bands), `VOICE_LAYERS` (foundation-first harmony build ladder), `LEARNING_STEPS` (practice sequence), `NOTATION_HELP` (lead-sheet/notation primers), `SOLFEGE_DEGREES` + `solfegeForDegree(n)`. Pure data; pickers and docs read the same source so they can't drift. |
+| `songCraft.js` | Canonical a cappella song-craft reference data rendered by the Songs Guide (`/songs/guide`) and reused by the Song editor: `RHYTHM_SHAPES` / `DIRGE_RHYTHM_SHAPES` (dirge & ballad pulse feels with BPM bands), `VOICE_LAYERS` (foundation-first harmony build ladder), `LEARNING_STEPS` (practice sequence), `NOTATION_HELP` (lead-sheet/notation primers), `SOLFEGE_DEGREES` + `solfegeForDegree(n)`, and `rhythmShapeLabel(id)` (human-readable "Slow 4/4 ballad · dirge (56–76 BPM)" label shared by the editor's picker and read view). Pure data; pickers and docs read the same source so they can't drift. |
| `songPlayback.js` | `createLayeredPlayer(takes)` — decode N recorded vocal takes and start them together on one shared `AudioContext` so they stack into a layered a cappella performance (sample-aligned, per-layer mute). Used by the Song editor's recording mixer. |
| `wrSceneCursor.js` | Resolve which script scene the editor caret sits in (`sceneAtCursor`, `sceneAnchorIndex`) — inverse of WorkEditor's jump-to-scene text search; drives the live render preview's "scene at cursor" target. |
| `writingGuide.js` | Canonical Writers Room reference data + craft principles rendered by the Guide page (`/writers-room/guide`): `WRITING_LENGTH_TARGETS` (microfiction→novel word/char bands), `BOOK_LENGTH_ESTIMATES` (page-based), `WRITING_PRINCIPLES`, `PLANNED_ANALYSES` (e.g. the emotional-roadmap evaluator), and `classifyByWordCount(n)` for labelling a draft's length. Future word-count gauges / length checks read from here so targets don't drift from the docs. |
diff --git a/client/src/pages/SongEditor.jsx b/client/src/pages/SongEditor.jsx
index 94bd98dcd3..b1527d95ed 100644
--- a/client/src/pages/SongEditor.jsx
+++ b/client/src/pages/SongEditor.jsx
@@ -41,7 +41,9 @@ import SongRecordings from '../components/songs/SongRecordings';
// instead of loading their embed.js. Returns null for anything that isn't a
// TikTok video URL — those references render as plain links.
const tiktokVideoId = (url) => {
- const m = /tiktok\.com\/(?:@[\w.-]+\/video|v|embed(?:\/v2)?|player\/v1)\/(\d+)/.exec(url || '');
+ // Anchor the host so look-alikes (nottiktok.com, evil.com/#tiktok.com/…)
+ // don't match — tiktok.com must be preceded by start, `//`, or a subdomain dot.
+ const m = /(?:^|\/\/|\.)tiktok\.com\/(?:@[\w.-]+\/video|v|embed(?:\/v2)?|player\/v1)\/(\d+)/.exec(url || '');
return m ? m[1] : null;
};
const tiktokEmbedSrc = (id) => `https://www.tiktok.com/player/v1/${id}`;
diff --git a/server/routes/songs.test.js b/server/routes/songs.test.js
index 6e0cbf0b63..be822d6c57 100644
--- a/server/routes/songs.test.js
+++ b/server/routes/songs.test.js
@@ -146,6 +146,17 @@ describe('songs route', () => {
expect(mocks.updateSong).not.toHaveBeenCalled();
});
+ it('PUT /:id accepts an empty-url reference (a blank row is dropped server-side, not rejected)', async () => {
+ // The editor seeds new reference rows as { url: '' }; saving must not 400 —
+ // the service drops the blank row. Guards against a future `.min(1)` that
+ // would reject in-progress rows on save.
+ mocks.updateSong.mockResolvedValue({ id: 'song-1' });
+ const res = await request(makeApp()).put('/api/songs/song-1').send({
+ references: [{ url: '' }],
+ });
+ expect(res.status).toBe(200);
+ });
+
it('POST /:id/refresh-template returns the refreshed built-in song', async () => {
mocks.refreshSongFromTemplate.mockResolvedValue({ id: 'seed-500-miles', title: '500 Miles', builtIn: true });
const res = await request(makeApp()).post('/api/songs/seed-500-miles/refresh-template');
diff --git a/server/services/songs.js b/server/services/songs.js
index becaa9c22c..f37a0c22bb 100644
--- a/server/services/songs.js
+++ b/server/services/songs.js
@@ -123,7 +123,10 @@ const sanitizeRecording = (r) => {
const sanitizeReference = (r) => {
if (!r || typeof r !== 'object') return null;
const url = trimField(r.url, URL_MAX_LENGTH);
- if (!url) return null;
+ // Require an http(s) scheme — defense-in-depth so a hand-edited file or a
+ // non-PortOS writer can't persist a javascript:/data: URL that a renderer
+ // might trust (mirrors the client's isHttpUrl guard).
+ if (!/^https?:\/\//i.test(url)) return null;
return {
id: trimField(r.id, ID_MAX_LENGTH) || `ref-${randomUUID().slice(0, 8)}`,
url,
@@ -304,11 +307,18 @@ export async function refreshSongFromTemplate(id) {
const template = seedTemplate(id);
if (!template) throw makeErr(`Song ${id} is not a built-in default`, ERR_NOT_BUILTIN);
const existing = songs[idx];
+ // Resetting layers to the template set can orphan a recording assigned to a
+ // user-added layer the template doesn't define — unassign those so the
+ // mixer doesn't reference a layer that no longer exists (the take still plays).
+ const templateLayerIds = new Set((template.layers || []).map((l) => l.id));
+ const recordings = (existing.recordings || []).map((r) => (
+ r.layerId && !templateLayerIds.has(r.layerId) ? { ...r, layerId: '' } : r
+ ));
const song = sanitizeSong({
...template,
id,
learned: existing.learned,
- recordings: existing.recordings,
+ recordings,
createdAt: existing.createdAt,
updatedAt: new Date().toISOString(),
});
diff --git a/server/services/songs.test.js b/server/services/songs.test.js
index 514523d370..dfce1d2de5 100644
--- a/server/services/songs.test.js
+++ b/server/services/songs.test.js
@@ -213,6 +213,33 @@ describe('songs service', () => {
expect(refreshed.builtIn).toBe(true);
});
+ it('unassigns a recording whose layer the template lacks when refreshing', async () => {
+ await svc.listSongs();
+ const seedId = [...svc.BUILTIN_SONG_IDS][0];
+ await svc.updateSong(seedId, {
+ layers: [{ id: 'custom-counter', label: 'Counter', part: 'Tenor' }],
+ recordings: [{ filename: 'take.wav', layerId: 'custom-counter' }],
+ });
+ const refreshed = await svc.refreshSongFromTemplate(seedId);
+ // Layers reset to the template set, so the custom layer is gone…
+ expect(refreshed.layers.some((l) => l.id === 'custom-counter')).toBe(false);
+ // …and the take that referenced it is unassigned rather than orphaned.
+ expect(refreshed.recordings).toHaveLength(1);
+ expect(refreshed.recordings[0].layerId).toBe('');
+ });
+
+ it('drops a non-http(s) reference url (defense-in-depth)', () => {
+ const song = svc.sanitizeSong({
+ id: 'x',
+ references: [
+ { url: 'javascript:alert(1)' }, // dangerous scheme → dropped
+ { url: 'https://www.tiktok.com/@u/video/1' },
+ ],
+ });
+ expect(song.references).toHaveLength(1);
+ expect(song.references[0].url).toBe('https://www.tiktok.com/@u/video/1');
+ });
+
it('refresh throws NOT_BUILTIN for a custom song and NOT_FOUND for a missing one', async () => {
const custom = await svc.createSong({ title: 'Mine' });
await expect(svc.refreshSongFromTemplate(custom.id)).rejects.toMatchObject({ code: svc.ERR_NOT_BUILTIN });