@openpeepshq/core 0.14.0 → 0.15.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.
@@ -33,8 +33,8 @@ export declare const storeFromPath: (filePath: string) => Promise<{
33
33
  }>;
34
34
  /**
35
35
  * Returns the on-disk file to store for the attachment plus its final
36
- * filename. Videos are transcoded to a temp `.mp4` (a fresh path); everything
37
- * else is stored as-is (the returned `path` is the input itself).
36
+ * filename. Videos and non-AAC audio are transcoded to temp files (fresh
37
+ * paths); everything else is stored as-is (the returned `path` is the input).
38
38
  */
39
39
  export declare const transcodeIncomingMedia: (type: string, inputPath: string, originalName: string, sourceMimetype: string) => Promise<MediaFile & {
40
40
  filename: string;
@@ -9,7 +9,7 @@ import { createReadStream, createWriteStream } from 'node:fs';
9
9
  import { Readable } from 'node:stream';
10
10
  import { pipeline } from 'node:stream/promises';
11
11
  import { spawn } from 'node:child_process';
12
- import { getTheme, randomString } from '@openpeepshq/common/lib';
12
+ import { getTheme, randomString, VOICE_NOTE_MAX_SECONDS, } from '@openpeepshq/common/lib';
13
13
  import { logger } from '../log/index.js';
14
14
  import { hub } from '../events/index.js';
15
15
  let storagePromise = null;
@@ -63,9 +63,41 @@ export const writeStorageToTemp = async (storageId, name) => {
63
63
  };
64
64
  /** Content-address and store a file by streaming it from disk. */
65
65
  export const storeFromPath = (filePath) => mediaStorage().then((storage) => storage.storeStream(Readable.toWeb(createReadStream(filePath))));
66
- const transcodeVideo = async (inputPath) => {
67
- const { size } = await fs.stat(inputPath);
68
- const isLargeFile = size > 10 * 1024 * 1024;
66
+ /**
67
+ * Normalizes any audio upload to MP4/AAC in a temp `.m4a` (a fresh path).
68
+ * Browsers record webm/ogg, which iOS cannot decode; AAC-in-MP4 plays on
69
+ * every client, so the uploaded format is never what ships.
70
+ */
71
+ const transcodeAudio = (inputPath) => {
72
+ const tempOutputPath = join(tmpdir(), `output-${randomString(16)}.m4a`);
73
+ return new Promise((resolve, reject) => {
74
+ ffmpeg(inputPath)
75
+ .noVideo()
76
+ .outputOptions('-c:a aac')
77
+ .outputOptions('-b:a 128k')
78
+ .output(tempOutputPath)
79
+ .on('end', () => resolve(tempOutputPath))
80
+ .on('error', (error) => reject(new Error(`Audio transcode failed: ${error}`)))
81
+ .run();
82
+ });
83
+ };
84
+ /**
85
+ * Probes a file's duration in seconds via ffprobe. Throws `MediaContentError`
86
+ * when the duration cannot be determined, so an unprobeable file fails closed
87
+ * as a 400 in the sync upload path (the handler maps `MediaContentError` to
88
+ * `badRequest`), not as an opaque 500.
89
+ */
90
+ const probeAudioDuration = (inputPath) => new Promise((resolve, reject) => {
91
+ ffmpeg.ffprobe(inputPath, (err, metadata) => {
92
+ const duration = metadata?.format?.duration;
93
+ if (err || !duration) {
94
+ reject(new MediaContentError(`Could not probe audio duration: ${err || 'no duration in metadata'}`));
95
+ return;
96
+ }
97
+ resolve(duration);
98
+ });
99
+ });
100
+ const transcodeVideo = (inputPath, isLargeFile) => {
69
101
  const tempOutputPath = join(tmpdir(), `output-${randomString(16)}.mp4`);
70
102
  const baseOutput = [
71
103
  '-c:v h264', // Better for iOS hardware acceleration
@@ -94,17 +126,54 @@ const transcodeVideo = async (inputPath) => {
94
126
  };
95
127
  /**
96
128
  * Returns the on-disk file to store for the attachment plus its final
97
- * filename. Videos are transcoded to a temp `.mp4` (a fresh path); everything
98
- * else is stored as-is (the returned `path` is the input itself).
129
+ * filename. Videos and non-AAC audio are transcoded to temp files (fresh
130
+ * paths); everything else is stored as-is (the returned `path` is the input).
99
131
  */
132
+ // Container + codec every client can decode: MP4/AAC is native on iOS and
133
+ // Android (react-native-sound) and playable by every browser. Browsers
134
+ // cannot record it directly, so webm/ogg uploads are normalized here. MP3
135
+ // (audio/mpeg) is normalized too: react-native-sound on iOS does not
136
+ // guarantee MP3 playback, so a picked MP3 would be silent on iOS even though
137
+ // it plays everywhere else.
100
138
  export const transcodeIncomingMedia = async (type, inputPath, originalName, sourceMimetype) => {
101
139
  if (type === 'video') {
140
+ const { size } = await fs.stat(inputPath);
141
+ const isLargeFile = size > 10 * 1024 * 1024;
102
142
  return {
103
- path: await transcodeVideo(inputPath),
143
+ path: await transcodeVideo(inputPath, isLargeFile),
104
144
  filename: path.parse(originalName).name + '.mp4',
105
145
  mimetype: 'video/mp4',
106
146
  };
107
147
  }
148
+ if (type === 'audio') {
149
+ // The voice-note cap is a single source of truth in common; the server
150
+ // enforces it too so a crafted upload cannot bypass the client cap.
151
+ //
152
+ // Boundary: `>` (not `>=`) — the recorders auto-stop at
153
+ // `VOICE_NOTE_AUTO_STOP_SECONDS` (half a second under the cap) so an
154
+ // honest take's probed duration lands strictly under 90 s, while a
155
+ // genuinely-overshot or crafted upload (≥ 90.5 s) probes at/above it.
156
+ // See the `VOICE_NOTE_MAX_SECONDS` docs.
157
+ const duration = await probeAudioDuration(inputPath);
158
+ if (duration > VOICE_NOTE_MAX_SECONDS) {
159
+ throw new MediaContentError(`Audio exceeds the ${VOICE_NOTE_MAX_SECONDS}s voice-note limit.`);
160
+ }
161
+ if (!['audio/mp4', 'audio/aac'].includes(sourceMimetype)) {
162
+ return {
163
+ path: await transcodeAudio(inputPath),
164
+ filename: path.parse(originalName).name + '.m4a',
165
+ mimetype: 'audio/mp4',
166
+ };
167
+ }
168
+ // Pass-through trade-off (round-17 item 2): `audio/mp4` and `audio/aac`
169
+ // are trusted by their reported/derived mimetype without re-probing
170
+ // container semantics. A video file renamed to `.mp4` but reported as
171
+ // `audio/mp4` would therefore be stored as an audio attachment with a
172
+ // video payload. The realistic exposure is small — the RN picker filters
173
+ // to audio and web's file input only accepts `audio/*` — so this is a
174
+ // documented trade rather than a byte-level container check (which would
175
+ // need full `mvhd`/`stsd` parsing, not just header sniffing).
176
+ }
108
177
  return { path: inputPath, filename: originalName, mimetype: sourceMimetype };
109
178
  };
110
179
  export const createPreview = async (inputPath, mimetype, originalName) => {
@@ -1,4 +1,20 @@
1
1
  import type { MediaAttachment } from '@openpeepshq/common/types';
2
+ /**
3
+ * Uploads smaller than this are processed synchronously in the request (the
4
+ * client gets the final attachment, or a 400 if processing rejects it); larger
5
+ * uploads go to the worker and the client is told "processing" first.
6
+ *
7
+ * Voice-note cap interaction: the server-side 90 s cap (VOICE_NOTE_MAX_SECONDS,
8
+ * enforced in `transcodeIncomingMedia`) only reaches the client as a
9
+ * fail-closed 400 on this sync path — a bigger upload bypasses the cap until
10
+ * the worker runs, after the client has already been told the attachment
11
+ * succeeded. The threshold must therefore stay above a realistic 90 s
12
+ * voice note so recorded notes take the sync path and the cap can reject them:
13
+ * a web note recorded at a low bitrate (opus, ~0.4 MB) is well under, and a
14
+ * high-bitrate AAC take (~128 kbps, ~1.4 MB) is only marginally above. Lowering
15
+ * this threshold toward typical note sizes would silently weaken that
16
+ * guarantee, so a change here is not a routine tuning.
17
+ */
2
18
  export declare const SYNC_PROCESSING_LIMIT: number;
3
19
  export interface RunProcessingInput {
4
20
  mediaAttachmentId: string;
@@ -5,6 +5,22 @@ import { logger } from '../log/index.js';
5
5
  import { withSpan } from '../performance/index.js';
6
6
  import { mediaStorage, transcodeIncomingMedia, createPreview, storeFromPath, writeStorageToTemp, writeStreamToTemp, } from './index.js';
7
7
  const log = logger('app:media:processing');
8
+ /**
9
+ * Uploads smaller than this are processed synchronously in the request (the
10
+ * client gets the final attachment, or a 400 if processing rejects it); larger
11
+ * uploads go to the worker and the client is told "processing" first.
12
+ *
13
+ * Voice-note cap interaction: the server-side 90 s cap (VOICE_NOTE_MAX_SECONDS,
14
+ * enforced in `transcodeIncomingMedia`) only reaches the client as a
15
+ * fail-closed 400 on this sync path — a bigger upload bypasses the cap until
16
+ * the worker runs, after the client has already been told the attachment
17
+ * succeeded. The threshold must therefore stay above a realistic 90 s
18
+ * voice note so recorded notes take the sync path and the cap can reject them:
19
+ * a web note recorded at a low bitrate (opus, ~0.4 MB) is well under, and a
20
+ * high-bitrate AAC take (~128 kbps, ~1.4 MB) is only marginally above. Lowering
21
+ * this threshold toward typical note sizes would silently weaken that
22
+ * guarantee, so a change here is not a routine tuning.
23
+ */
8
24
  export const SYNC_PROCESSING_LIMIT = Number(process.env.MEDIA_SYNC_PROCESSING_LIMIT || 1024 * 1024);
9
25
  /**
10
26
  * Transcode + generate a preview for an attachment, working entirely with
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openpeepshq/core",
3
- "version": "0.14.0",
3
+ "version": "0.15.0",
4
4
  "type": "module",
5
5
  "license": "GPL-3.0-or-later",
6
6
  "dependencies": {
@@ -37,10 +37,10 @@
37
37
  "type-fest": "^4.31.0",
38
38
  "uuidv7": "^1.0.2",
39
39
  "web-push": "^3.6.7",
40
- "@openpeepshq/common": "0.15.0",
40
+ "@openpeepshq/common": "0.16.0",
41
41
  "@openpeepshq/fetch-client": "^0.2.1",
42
42
  "@openpeepshq/geocoder": "^0.1.2",
43
- "@openpeepshq/i18n": "^0.16.0"
43
+ "@openpeepshq/i18n": "^0.17.0"
44
44
  },
45
45
  "main": "dist/index.js",
46
46
  "types": "dist/index.d.ts",