@yourname168/tiktok 0.0.0-stage → 0.1.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.
package/LICENSE ADDED
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) contributors. Derived portions remain copyright their respective
4
+ upstream authors as listed in THIRD_PARTY_NOTICES.md.
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,127 @@
1
- # Temporary Holding Version
1
+ # @yourname168/tiktok — direct TikTok clients (experimental)
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Install the published package (Node.js 24):
4
+
5
+ ```sh
6
+ npm install @yourname168/tiktok
7
+ ```
8
+
9
+ The workspace uses the internal name `@gateway/tiktok`; npm releases use
10
+ `@yourname168/tiktok`. Use the published name in imports after npm installation.
11
+
12
+ Node.js 24 library reconstructed from the HTTP behavior of
13
+ `n8n-nodes-social-tiktok@0.1.22` and `@igabm/n8n-nodes-tiktok@1.5.0`.
14
+ No n8n server, node execution context, upstream npm package, WebAssembly,
15
+ browser polyfill, or background process is required at runtime.
16
+
17
+ ## TikTok Shop / web-session client
18
+
19
+ ```ts
20
+ import { readFile } from 'node:fs/promises';
21
+ import { createTikTokWebClient } from '@yourname168/tiktok';
22
+
23
+ const client = createTikTokWebClient({
24
+ session: JSON.parse(await readFile('/private/tiktok-session.json', 'utf8')),
25
+ carrierRegion: 'VN',
26
+ });
27
+
28
+ const products = await client.getShowcaseProducts({ count: 6 });
29
+ console.log(products.map(({ productId, title }) => ({ productId, title })));
30
+
31
+ // Choose an intended product explicitly before calling this mutating method.
32
+ // const result = await client.uploadVideo({
33
+ // videoPath: '/absolute/path/video.mp4',
34
+ // caption: 'Giới thiệu sản phẩm #shop',
35
+ // visibility: 'public',
36
+ // products: [{ productId: 'chosen-product-id', displayName: 'Tên sản phẩm' }],
37
+ // });
38
+ ```
39
+
40
+ Session format is the JSON expected by Botzvn, not a raw sessionid string:
41
+
42
+ ```json
43
+ {
44
+ "http": {
45
+ "headers": { "Cookie": "sessionid=...", "User-Agent": "your browser user agent" },
46
+ "params": { "msToken": "...", "odinId": "...", "tz_name": "Asia/Ho_Chi_Minh" }
47
+ }
48
+ }
49
+ ```
50
+
51
+ Keep session files outside version control. The library does not acquire sessions.
52
+ `getShowcaseProducts()` returns normalized `{ productId, title, raw }` items.
53
+ `uploadVideo()` uploads video bytes, attaches the explicitly selected products,
54
+ and publishes. It defaults to **private**; there is no automatic retry.
55
+ `publishVideo()` publishes an already uploaded `{ videoId, width, height }` asset.
56
+ The result is the raw validated response, not a guarantee that moderation or
57
+ processing completed. Reuse a known `creationId` and inspect TikTok before
58
+ retrying after a timeout; this library does not claim server-side idempotency.
59
+
60
+ Optional `coverUri` references an already uploaded cover. Uploading a cover file
61
+ is not ported. Scheduling accepts Unix seconds, at least 20 minutes in the future.
62
+ `carrierRegion` defaults to `TH` to match upstream; configure the actual region.
63
+ `transport` and `now` can be injected for tests, controlled networking and clocks.
64
+ A proxy can be implemented in a supplied transport; there is no global proxy state.
65
+
66
+ ## Official Content Posting API client
67
+
68
+ ```ts
69
+ import { createTikTokContentClient, refreshTikTokToken } from '@yourname168/tiktok';
70
+ const client = createTikTokContentClient({ accessToken: process.env.TIKTOK_ACCESS_TOKEN! });
71
+ const profile = await client.getUserProfile();
72
+ // await client.publishVideoFromUrl({
73
+ // videoUrl: 'https://your-verified-domain.example/video.mp4',
74
+ // caption: 'Demo', privacyLevel: 'SELF_ONLY',
75
+ // });
76
+ // await client.getPostStatus('publish-id');
77
+ ```
78
+
79
+ This client uses OAuth tokens and the official API, with no product anchors.
80
+ It ports profile, status, video-from-URL and refresh-token operations. Photo posts,
81
+ file-based official upload and interactive OAuth authorization are not ported.
82
+
83
+ ## Verification and limits
84
+
85
+ - Golden vectors from the original npm code cover both web signatures, VOD SigV4
86
+ and the complete web post body. Signer entropy/time are fixed only in tests.
87
+ - Offline HTTP tests exercise upload/auth → apply → init → transfer → finish →
88
+ commit → attach products → publish; account cookies never go to storage hosts.
89
+ - **No live account call or real publish has been performed.** Private web APIs
90
+ can change independently of the npm package. Treat this as an experimental port.
91
+ - VOD upload currently ports the normal multipart route. Gateway/stream uploads,
92
+ dynamic slice rules, resume, retries, image upload, messaging, triggers, hashtag
93
+ lookup and comments are not ported. Storage hosts are restricted in vod-upload.ts.
94
+ - Header/payload logic is rewritten in TypeScript. X-Bogus is reconstructed as
95
+ readable JavaScript; X-Gnarly is recovered JavaScript with decoded strings and
96
+ some generated local names still present. Neither imports the original package.
97
+
98
+ Run from the repository:
99
+
100
+ ```sh
101
+ pnpm exec vitest run packages/tiktok/src/tiktok.test.ts
102
+ pnpm exec tsc -p packages/tiktok/tsconfig.json --noEmit
103
+ ```
104
+
105
+ Workspace consumers import source, as established by repository conventions.
106
+ For installation outside the monorepo, generate a compiled JS + declaration tarball:
107
+
108
+ ```sh
109
+ pnpm --filter @gateway/tiktok pack:portable /absolute/output/directory
110
+ npm install /absolute/output/directory/gateway-tiktok-0.1.0.tgz
111
+ ```
112
+
113
+ Use this portable tarball instead of packing the TypeScript workspace directly:
114
+ Node 24 does not strip TypeScript inside node_modules.
115
+
116
+ See [REVERSE_NOTES.md](./REVERSE_NOTES.md) for the request map and provenance,
117
+ and [THIRD_PARTY_NOTICES.md](./THIRD_PARTY_NOTICES.md) for attribution.
118
+
119
+ To prepare a public release under the npm account scope:
120
+
121
+ ```sh
122
+ pnpm --filter @gateway/tiktok pack:portable /absolute/output/directory --name @yourname168/tiktok
123
+ npm publish /absolute/output/directory/yourname168-tiktok-0.1.0.tgz --access public
124
+ ```
125
+
126
+ The public tarball excludes tests, session files, npm credentials and workspace
127
+ configuration. The workspace package remains private.
@@ -0,0 +1,62 @@
1
+ # Reverse engineering notes — 2026-11-16
2
+
3
+ Inspected pinned npm artifacts; decoded string-table/RC4 lookups and folded
4
+ constants, then traced the node methods and uploader SDK. No user session was
5
+ read and no TikTok account endpoint was invoked. Discarded the initial node-wrapper
6
+ approach. The runtime package has zero npm dependencies.
7
+
8
+ ## Botzvn request map
9
+
10
+ | Stage | Request | Evidence |
11
+ |---|---|---|
12
+ | Showcase | GET `https://shop.tiktok.com/api/v1/streamer_desktop/showcase_product/list?count=6&offset=0` | TuxTux.executeProductgetShowcaseProducts |
13
+ | STS token | GET `https://www.tiktok.com/api/v1/video/upload/auth/?aid=1988&msToken=...` | xU.getSTSTokenFromSession |
14
+ | Apply VOD | GET `https://www.tiktok.com/top/v1?Action=ApplyUploadInner&Version=2020-11-19&SpaceName=tiktok&FileType=video&IsInner=1&FileSize=...` | xUW uploader |
15
+ | Init storage | POST `/upload/v1/{StoreUri}?uploadmode=part&phase=init` | xUW initUpload |
16
+ | Transfer | POST `/upload/v1/{StoreUri}?uploadid=...&part_number=...&phase=transfer` | xUW uploadChunkedUrl |
17
+ | Finish storage | POST `/upload/v1/{StoreUri}?uploadmode=part&phase=finish&uploadid=...`, body `1:crc,2:crc` | xUW mergeFile |
18
+ | Commit VOD | POST `/top/v1?Action=CommitUploadInner&Version=2020-11-19&SpaceName=tiktok`, body SessionKey/Functions | xUW commitUpload |
19
+ | Attach products | OPTIONS then POST `https://shop.tiktok.com/aweme/v1/oec/content/creator/products?aid=1180&carrier_region=TH` | xP.addProductFromAnchors |
20
+ | Publish | POST `https://www.tiktok.com/tiktok/web/project/post/v1/` | xU.postVideo |
21
+
22
+ Product attachment sends `{add_targets:[5], products:[{product_id:...}]}`.
23
+ The final post carries anchor type33, content.add_from2, product_id and a display
24
+ keyword limited to30 UTF-16 code units. VOD requests use AWS4-HMAC-SHA256,
25
+ region ap-singapore-1/service vod. Storage uses returned Auth and X-Storage-U,
26
+ not the account cookie. Publish serializes the body first, signs the initial query
27
+ with X-Bogus, then signs query+X-Bogus with X-Gnarly version5.1.1. Both signatures
28
+ bind query/body/user agent/time; X-Gnarly also uses entropy/state.
29
+
30
+ The normal VOD route is a reconstruction of the SDK's separate apply/transfer/
31
+ commit branches. It is not a claim that all current TikTok accounts select that
32
+ route. Botzvn also supports merged post-upload and other server-selected variants;
33
+ those are outside this port. No rate limits, quota checks, challenges or account
34
+ permissions were disabled or bypassed.
35
+
36
+ ## Official package map
37
+
38
+ OAuth bearer token calls to `https://open.tiktokapis.com/v2`:
39
+ GET `/user/info/`, POST `/post/publish/video/init/`, POST
40
+ `/post/publish/status/fetch/`; token refresh is form-encoded POST `/oauth/token/`.
41
+ No TikTok Shop anchor fields occur in that node's video request.
42
+
43
+ ## Reproducibility evidence
44
+
45
+ Golden JSON fixtures were generated directly from the pinned original functions.
46
+ Signature vectors control Date.now, crypto.randomInt/randomBytes and Math.random
47
+ inside an isolated VM; this control is only in verification, never production.
48
+ VOD golden headers come from xUW's original pi signer. Post payload fixture comes
49
+ from xU.createPostBody. The implementation tests consume only retained fixtures,
50
+ not home directories or the demo n8n installation.
51
+
52
+ Original files SHA-256:
53
+
54
+ | File in Botzvn dist | SHA-256 |
55
+ |---|---|
56
+ | `nodes/Tiktok/TuxTux.node.js` | `8c6b00669bdb641744be7618fecca6ef4e93fbb61ff6a4e0e5860e0ef3c66906` |
57
+ | `nodes/Tiktok/VxVx.node.js` | `bafab44d64a7c8db33008340cade615de39a0be7c57887e8ed5d3dc0921ef6f0` |
58
+ | `utils/xP.js` | `638eb478c116bbf634229cfd7f065c30fee3edc4b2ef00581529aeb1d2fe31e0` |
59
+ | `utils/xU.js` | `77800ef0c24f6dece17c7c9b26c1d47e4fa037f9fb35c0a2159f8a9bf437c0f4` |
60
+ | `utils/xB.js` | `e86247fa31c35e61f21f67a07492306f2b18da710986d251392ecb1f3b069263` |
61
+ | `utils/xG.js` | `4e03a633160a9ba419b09cd7e8eafa66ed30942ad52e6eaf600dbc8a274275f7` |
62
+ | `utils/xUW.js` | `0b644d3dec968134198df5576482c12637c56d360ad0a28263236f5f90d7a706` |
@@ -0,0 +1,44 @@
1
+ # Third-party attribution
2
+
3
+ ## n8n-nodes-social-tiktok 0.1.22
4
+
5
+ Author in npm metadata: hieu nguyen (Botzvn).
6
+ Declared license: MIT. Repository declared by npm:
7
+ https://github.com/botzvn/n8n-nodes-social-tiktok (returned 404 during this work).
8
+
9
+ The recovered X-Bogus/X-Gnarly algorithms and the protocol reconstruction derive
10
+ from this published package. Original names and author attribution are retained
11
+ here. No claim is made that the GitHub workflow repository is the source of the
12
+ underlying node implementation. The npm tarball contains no separate LICENSE file;
13
+ the license evidence is its package.json metadata.
14
+
15
+ ## @igabm/n8n-nodes-tiktok 1.5.0
16
+
17
+ Author in npm metadata: Gabriel MATIAS. Declared license: MIT.
18
+ https://github.com/igabm/n8n-nodes-tiktok
19
+
20
+ Used to study official API paths, authentication and payload shapes. The official
21
+ client here is independently written against those request shapes; the package is
22
+ not a runtime dependency.
23
+
24
+ ## MIT license terms for derived portions
25
+
26
+ Copyright belongs to the respective upstream authors.
27
+
28
+ Permission is hereby granted, free of charge, to any person obtaining a copy
29
+ of this software and associated documentation files (the "Software"), to deal
30
+ in the Software without restriction, including without limitation the rights
31
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
32
+ copies of the Software, and to permit persons to whom the Software is
33
+ furnished to do so, subject to the following conditions:
34
+
35
+ The above copyright notice and this permission notice shall be included in all
36
+ copies or substantial portions of the Software.
37
+
38
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
39
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
40
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
41
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
42
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
43
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
44
+ SOFTWARE.
@@ -0,0 +1,21 @@
1
+ import type { HttpTransport, JsonObject } from './http.ts';
2
+ export declare function createTikTokContentClient(options: {
3
+ accessToken: string;
4
+ transport?: HttpTransport;
5
+ timeoutMs?: number;
6
+ }): {
7
+ getUserProfile(fields?: string[]): Promise<JsonObject>;
8
+ getPostStatus(publishId: string): Promise<JsonObject>;
9
+ publishVideoFromUrl(input: {
10
+ videoUrl: string;
11
+ caption: string;
12
+ privacyLevel: string;
13
+ disableComment?: boolean;
14
+ }): Promise<JsonObject>;
15
+ };
16
+ export declare function refreshTikTokToken(input: {
17
+ clientKey: string;
18
+ clientSecret: string;
19
+ refreshToken: string;
20
+ transport?: HttpTransport;
21
+ }): Promise<JsonObject>;
@@ -0,0 +1,27 @@
1
+ import { createHttp, object, string } from "./http.js";
2
+ export function createTikTokContentClient(options) {
3
+ const token = string(options.accessToken, 'accessToken'), request = createHttp(options.transport, options.timeoutMs);
4
+ const headers = { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' };
5
+ const post = (path, body) => request(`https://open.tiktokapis.com/v2${path}`, { method: 'POST', headers, body: JSON.stringify(body) });
6
+ return {
7
+ async getUserProfile(fields = ['open_id', 'display_name', 'avatar_url']) {
8
+ if (!fields.length || fields.some(f => !/^[a-z_]+$/.test(f)))
9
+ throw new Error('Invalid profile fields');
10
+ return object((await request(`https://open.tiktokapis.com/v2/user/info/?${new URLSearchParams({ fields: fields.join(',') })}`, { method: 'GET', headers })).data);
11
+ },
12
+ async getPostStatus(publishId) { return object((await post('/post/publish/status/fetch/', { publish_id: string(publishId, 'publishId') })).data); },
13
+ async publishVideoFromUrl(input) {
14
+ const url = new URL(input.videoUrl);
15
+ if (url.protocol !== 'https:')
16
+ throw new Error('Video URL must use HTTPS');
17
+ if (!['PUBLIC_TO_EVERYONE', 'MUTUAL_FOLLOW_FRIENDS', 'FOLLOWER_OF_CREATOR', 'SELF_ONLY'].includes(input.privacyLevel))
18
+ throw new Error('Invalid privacyLevel');
19
+ return object((await post('/post/publish/video/init/', { post_info: { title: input.caption, privacy_level: input.privacyLevel, disable_comment: input.disableComment ?? false }, source_info: { source: 'PULL_FROM_URL', video_url: url.toString() } })).data);
20
+ },
21
+ };
22
+ }
23
+ export async function refreshTikTokToken(input) {
24
+ const body = new URLSearchParams({ client_key: string(input.clientKey, 'clientKey'), client_secret: string(input.clientSecret, 'clientSecret'),
25
+ refresh_token: string(input.refreshToken, 'refreshToken'), grant_type: 'refresh_token' });
26
+ return createHttp(input.transport)('https://open.tiktokapis.com/v2/oauth/token/', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: body.toString() });
27
+ }
package/dist/http.d.ts ADDED
@@ -0,0 +1,5 @@
1
+ export type JsonObject = Record<string, unknown>;
2
+ export declare function object(value: unknown): JsonObject;
3
+ export declare function string(value: unknown, field: string): string;
4
+ export type HttpTransport = (url: string, init: RequestInit) => Promise<Response>;
5
+ export declare function createHttp(transport?: HttpTransport, timeoutMs?: number): (url: string, init: RequestInit) => Promise<JsonObject>;
package/dist/http.js ADDED
@@ -0,0 +1,42 @@
1
+ export function object(value) {
2
+ if (!value || typeof value !== 'object' || Array.isArray(value))
3
+ throw new Error('Invalid TikTok response object');
4
+ return value;
5
+ }
6
+ export function string(value, field) {
7
+ if (typeof value !== 'string' || !value.trim())
8
+ throw new Error(`Missing ${field}`);
9
+ return value;
10
+ }
11
+ export function createHttp(transport = fetch, timeoutMs = 120_000) {
12
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1)
13
+ throw new Error('Invalid timeoutMs');
14
+ return async (url, init) => {
15
+ let response;
16
+ try {
17
+ response = await transport(url, { ...init, redirect: 'error', signal: AbortSignal.timeout(timeoutMs) });
18
+ }
19
+ catch {
20
+ throw new Error('TikTok network request failed; verify status before retrying a publish');
21
+ }
22
+ if (!response.ok)
23
+ throw new Error(`TikTok HTTP ${response.status}`);
24
+ if (response.status === 204 || init.method === 'OPTIONS')
25
+ return {};
26
+ let value;
27
+ try {
28
+ value = await response.json();
29
+ }
30
+ catch {
31
+ throw new Error('TikTok returned invalid JSON');
32
+ }
33
+ const data = object(value);
34
+ const metadata = data.ResponseMetadata;
35
+ const apiError = data.error;
36
+ if ((metadata && object(metadata).Error) || (apiError && object(apiError).code !== undefined && object(apiError).code !== 'ok') ||
37
+ (data.status_code !== undefined && data.status_code !== 0) || (data.code !== undefined && data.code !== 0)) {
38
+ throw new Error('TikTok rejected the request');
39
+ }
40
+ return data;
41
+ };
42
+ }
@@ -0,0 +1,7 @@
1
+ export { createTikTokWebClient } from './web-client.ts';
2
+ export { createTikTokContentClient, refreshTikTokToken } from './content-client.ts';
3
+ export { parseTikTokSession } from './session.ts';
4
+ export { createWebPostBody, productAnchors } from './post-body.ts';
5
+ export type { TikTokSession } from './session.ts';
6
+ export type { ProductAnchor, UploadedVideo, WebPostOptions } from './post-body.ts';
7
+ export type { HttpTransport } from './http.ts';
package/dist/index.js ADDED
@@ -0,0 +1,4 @@
1
+ export { createTikTokWebClient } from "./web-client.js";
2
+ export { createTikTokContentClient, refreshTikTokToken } from "./content-client.js";
3
+ export { parseTikTokSession } from "./session.js";
4
+ export { createWebPostBody, productAnchors } from "./post-body.js";
@@ -0,0 +1,97 @@
1
+ export interface ProductAnchor {
2
+ productId: string;
3
+ displayName: string;
4
+ }
5
+ export interface UploadedVideo {
6
+ videoId: string;
7
+ width: number;
8
+ height: number;
9
+ }
10
+ export interface WebPostOptions {
11
+ creationId: string;
12
+ caption: string;
13
+ video: UploadedVideo;
14
+ coverUri?: string;
15
+ visibility?: 'public' | 'friends' | 'private';
16
+ allowComments?: boolean;
17
+ scheduleTimeSeconds?: number;
18
+ products?: ProductAnchor[];
19
+ }
20
+ export declare function productAnchors(products: ProductAnchor[]): {
21
+ type: number;
22
+ keyword: string;
23
+ content: {
24
+ add_from: number;
25
+ keyword: string;
26
+ product_id: string;
27
+ };
28
+ }[];
29
+ export declare function createWebPostBody(input: WebPostOptions): {
30
+ post_common_info: {
31
+ creation_id: string;
32
+ enter_post_page_from: number;
33
+ post_type: number;
34
+ };
35
+ feature_common_info_list: {
36
+ schedule_time: number;
37
+ geofencing_regions: never[];
38
+ playlist_name: string;
39
+ playlist_id: string;
40
+ tcm_params: string;
41
+ sound_exemption: number;
42
+ anchors: {
43
+ type: number;
44
+ keyword: string;
45
+ content: {
46
+ add_from: number;
47
+ keyword: string;
48
+ product_id: string;
49
+ };
50
+ }[];
51
+ vedit_common_info: {
52
+ draft: string;
53
+ video_id: string;
54
+ };
55
+ privacy_setting_info: {
56
+ visibility_type: number;
57
+ allow_duet: null;
58
+ allow_stitch: null;
59
+ allow_comment: number;
60
+ allow_content_reuse: number;
61
+ };
62
+ content_check_id: string;
63
+ }[];
64
+ single_post_req_list: {
65
+ batch_index: number;
66
+ video_id: string;
67
+ is_long_video: number;
68
+ single_post_feature_info: {
69
+ text: string;
70
+ text_extra: {
71
+ tag_id: string;
72
+ user_id: string;
73
+ start: number;
74
+ end: number;
75
+ type: number;
76
+ hashtag_name: string | undefined;
77
+ }[];
78
+ markup_text: string;
79
+ music_info: {};
80
+ cover_info: {
81
+ frame_duration: number;
82
+ blob_url: string;
83
+ cover_width: number;
84
+ cover_height: number;
85
+ cover_type: number;
86
+ crop_type: number;
87
+ isAutoCropFirstFrame: boolean;
88
+ cover_uri: string;
89
+ isProcessingInitialCover: boolean;
90
+ };
91
+ poster_delay: number;
92
+ cloud_edit_video_height: number;
93
+ cloud_edit_video_width: number;
94
+ cloud_edit_is_use_video_canvas: boolean;
95
+ };
96
+ }[];
97
+ };
@@ -0,0 +1,42 @@
1
+ import { string } from "./http.js";
2
+ export function productAnchors(products) {
3
+ return products.map(product => {
4
+ const keyword = string(product.displayName, 'displayName').slice(0, 30);
5
+ return { type: 33, keyword, content: { add_from: 2, keyword, product_id: string(product.productId, 'productId') } };
6
+ });
7
+ }
8
+ export function createWebPostBody(input) {
9
+ string(input.creationId, 'creationId');
10
+ string(input.video.videoId, 'videoId');
11
+ for (const n of [input.video.width, input.video.height])
12
+ if (!Number.isSafeInteger(n) || n < 1)
13
+ throw new Error('Invalid video dimensions');
14
+ const schedule = input.scheduleTimeSeconds ?? 0;
15
+ if (!Number.isSafeInteger(schedule) || schedule < 0)
16
+ throw new Error('Invalid scheduleTimeSeconds');
17
+ const visibility = input.visibility ?? 'private';
18
+ if (!['public', 'friends', 'private'].includes(visibility))
19
+ throw new Error('Invalid visibility');
20
+ const matches = [...input.caption.matchAll(/#(\w+)/g)];
21
+ const text_extra = matches.map((match, index) => ({ tag_id: String(index), user_id: '', start: match.index, end: match.index + match[0].length, type: 1, hashtag_name: match[1] }));
22
+ let markup_text = '';
23
+ let offset = 0;
24
+ matches.forEach((match, index) => {
25
+ markup_text += input.caption.slice(offset, match.index).replaceAll('\n', '<br>') + `<h id="${index}">${match[0]}</h>`;
26
+ offset = match.index + match[0].length;
27
+ });
28
+ markup_text += input.caption.slice(offset).replaceAll('\n', '<br>');
29
+ return {
30
+ post_common_info: { creation_id: input.creationId, enter_post_page_from: 2, post_type: 3 },
31
+ feature_common_info_list: [{ schedule_time: schedule, geofencing_regions: [], playlist_name: '', playlist_id: '',
32
+ tcm_params: '{"commerce_toggle_info":{}}', sound_exemption: 0, anchors: productAnchors(input.products ?? []),
33
+ vedit_common_info: { draft: '', video_id: input.video.videoId },
34
+ privacy_setting_info: { visibility_type: { public: 0, friends: 2, private: 1 }[visibility], allow_duet: null,
35
+ allow_stitch: null, allow_comment: input.allowComments === false ? 0 : 1, allow_content_reuse: 1 }, content_check_id: '' }],
36
+ single_post_req_list: [{ batch_index: 0, video_id: input.video.videoId, is_long_video: 0,
37
+ single_post_feature_info: { text: input.caption, text_extra, markup_text, music_info: {},
38
+ cover_info: { frame_duration: 0, blob_url: '', cover_width: input.video.width, cover_height: input.video.height,
39
+ cover_type: 2, crop_type: 2, isAutoCropFirstFrame: true, cover_uri: input.coverUri ?? '', isProcessingInitialCover: false },
40
+ poster_delay: 0, cloud_edit_video_height: input.video.height, cloud_edit_video_width: input.video.width, cloud_edit_is_use_video_canvas: false } }],
41
+ };
42
+ }
@@ -0,0 +1,33 @@
1
+ /* Derived from n8n-nodes-social-tiktok 0.1.22 (hieu nguyen), MIT.
2
+ * Reconstructed algorithm; see ../../THIRD_PARTY_NOTICES.md. */
3
+ // CommonJS keeps the recovered signer usable from plain Node and VM vectors.
4
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
5
+ const crypto = require('node:crypto');
6
+ const alphabet = 'Dkdpgh4ZKsQB80/Mfvw36XI1R25-WUAlEi7NLboqYTOPuzmFjJnryx9HVGcaStCe';
7
+ const standard = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
8
+ function md5(bytes) { return crypto.createHash('md5').update(bytes).digest(); }
9
+ function rc4(key, data) {
10
+ const state = Uint8Array.from({ length: 256 }, (_, i) => i);
11
+ let j = 0;
12
+ for (let i = 0; i < 256; i++) { j = (j + state[i] + key[i % key.length]) & 255; [state[i], state[j]] = [state[j], state[i]]; }
13
+ const out = Buffer.alloc(data.length);
14
+ let i = 0; j = 0;
15
+ for (let n = 0; n < data.length; n++) {
16
+ i = (i + 1) & 255; j = (j + state[i]) & 255; [state[i], state[j]] = [state[j], state[i]];
17
+ out[n] = data[n] ^ state[(state[i] + state[j]) & 255];
18
+ }
19
+ return out;
20
+ }
21
+ function encrypt(query, body, userAgent, nowSeconds) {
22
+ const key = Buffer.from([0, 1, 14]);
23
+ const queryHash = md5(md5(Buffer.from(query, 'utf8')));
24
+ const bodyHash = md5(md5(Buffer.from(body, 'utf8')));
25
+ const agentHash = md5(Buffer.from(rc4(key, Buffer.from(userAgent, 'utf8')).toString('base64'), 'ascii'));
26
+ const timestamp = Buffer.alloc(4); timestamp.writeUInt32BE(nowSeconds >>> 0);
27
+ const magic = Buffer.alloc(4); magic.writeUInt32BE(1245783967);
28
+ const bytes = Buffer.concat([Buffer.from([64]), key, queryHash.subarray(14, 16), bodyHash.subarray(14, 16), agentHash.subarray(14, 16), timestamp, magic]);
29
+ const checksum = bytes.reduce((result, byte) => result ^ byte, 0);
30
+ const output = Buffer.concat([Buffer.from([2, 255]), rc4(Buffer.from([255]), Buffer.concat([bytes, Buffer.from([checksum])]))]);
31
+ return [...output.toString('base64')].map(char => { const index = standard.indexOf(char); return index < 0 ? char : alphabet[index]; }).join('');
32
+ }
33
+ module.exports = { encrypt };
@@ -0,0 +1,225 @@
1
+ /* Recovered from n8n-nodes-social-tiktok 0.1.22 (hieu nguyen), MIT. See ../../THIRD_PARTY_NOTICES.md. */
2
+ /* eslint-disable */
3
+ const crypto = require("crypto");
4
+ const aa = [4294967295, 138, 1498001188, 211147047, 253, null, 203, 288, 9, 1196819126, 3212677781, 135, 263, 193, 58, 18, 244, 2931180889, 240, 173, 268, 2157053261, 261, 175, 14, 5, 171, 270, 156, 258, 13, 15, 3732962506, 185, 169, 2, 6, 132, 162, 200, 3, 160, 217618912, 62, 2517678443, 44, 164, 4, 96, 183, 2903579748, 3863347763, 119, 181, 10, 190, 8, 2654435769, 259, 104, 230, 128, 2633865432, 225, 1, 257, 143, 179, 16, 600974999, 185100057, 32, 188, 53, 2718276124, 177, 196, 4294967296, 147, 117, 17, 49, 7, 28, 12, 266, 216, 11, 0, 45, 166, 247, 1451689750];
5
+ const Ot = [aa[9], aa[69], aa[51], aa[92]];
6
+ function initPrngState() {
7
+ const _0x32a8ae = {};
8
+ _0x32a8ae["vDnhB"] = function (_0x5947f2, _0x36f478) { return _0x5947f2 & _0x36f478; };
9
+ const _0xccb6a8 = _0x32a8ae, _0x80ddf5 = Date["now"]();
10
+ return [aa[44], aa[74], aa[10], aa[62], aa[42], aa[17], aa[2], aa[21], aa[3], aa[70], aa[50], aa[32], _0xccb6a8["vDnhB"](aa[0], _0x80ddf5), crypto["randomInt"](aa[77]), crypto["randomInt"](aa[77]), crypto["randomInt"](aa[77])];
11
+ }
12
+ let kt = initPrngState();
13
+ let St = aa[88];
14
+ const u32 = _0x14581a => _0x14581a >>> 0;
15
+ const rotl = (_0x52a1f6, _0x5d00d7) => u32(_0x52a1f6 << _0x5d00d7 | _0x52a1f6 >>> 32 - _0x5d00d7);
16
+ function quarter(_0x2e5678, _0xc71fde, _0x264633, _0x1d02be, _0x39a253) {
17
+ const _0x451393 = { 'rGfRu': function (_0x4a95e2, _0x20b7e9) { return _0x4a95e2(_0x20b7e9); }, 'jQWjR': function (_0x2e4db8, _0x26eeb8) { return _0x2e4db8 + _0x26eeb8; }, 'EcOjb': function (_0x80c41a, _0x3330a6) { return _0x80c41a(_0x3330a6); }, 'hrQkc': function (_0x56c5de, _0x370f35) { return _0x56c5de ^ _0x370f35; }, 'zXcov': function (_0x31212d, _0x6df8ac) { return _0x31212d ^ _0x6df8ac; } }, _0x194be7 = ("0|7|2|5|6|4|1|3")["split"]('|');
18
+ let _0xe41c5d = 0;
19
+ while (!![]) {
20
+ switch (_0x194be7[_0xe41c5d++]) {
21
+ case '0':
22
+ _0x2e5678[_0xc71fde] = _0x451393["rGfRu"](u32, _0x2e5678[_0xc71fde] + _0x2e5678[_0x264633]);
23
+ continue;
24
+ case '1':
25
+ _0x2e5678[_0x1d02be] = _0x451393["rGfRu"](u32, _0x451393["jQWjR"](_0x2e5678[_0x1d02be], _0x2e5678[_0x39a253]));
26
+ continue;
27
+ case '2':
28
+ _0x2e5678[_0x1d02be] = _0x451393["EcOjb"](u32, _0x451393["jQWjR"](_0x2e5678[_0x1d02be], _0x2e5678[_0x39a253]));
29
+ continue;
30
+ case '3':
31
+ _0x2e5678[_0x264633] = rotl(_0x451393["hrQkc"](_0x2e5678[_0x264633], _0x2e5678[_0x1d02be]), 7);
32
+ continue;
33
+ case '4':
34
+ _0x2e5678[_0x39a253] = rotl(_0x451393["zXcov"](_0x2e5678[_0x39a253], _0x2e5678[_0xc71fde]), 8);
35
+ continue;
36
+ case '5':
37
+ _0x2e5678[_0x264633] = rotl(_0x2e5678[_0x264633] ^ _0x2e5678[_0x1d02be], 12);
38
+ continue;
39
+ case '6':
40
+ _0x2e5678[_0xc71fde] = _0x451393["EcOjb"](u32, _0x451393["jQWjR"](_0x2e5678[_0xc71fde], _0x2e5678[_0x264633]));
41
+ continue;
42
+ case '7':
43
+ _0x2e5678[_0x39a253] = rotl(_0x451393["hrQkc"](_0x2e5678[_0x39a253], _0x2e5678[_0xc71fde]), 16);
44
+ continue;
45
+ }
46
+ break;
47
+ }
48
+ }
49
+ function chachaBlock(_0x394d50, _0x134952) {
50
+ const _0x5995c3 = { 'jEcqb': "jyUlm", 'QNwIH': function (_0x540418, _0xf697ef, _0x48c9f0, _0x5920d5, _0x843720, _0x4e7d90) { return _0x540418(_0xf697ef, _0x48c9f0, _0x5920d5, _0x843720, _0x4e7d90); }, 'zIpWr': function (_0x550168, _0x434eb8) { return _0x550168 >= _0x434eb8; }, 'KsqpY': function (_0x537a10, _0x5bd945, _0x4971da, _0x5c3cd4, _0x277440, _0x1b0862) { return _0x537a10(_0x5bd945, _0x4971da, _0x5c3cd4, _0x277440, _0x1b0862); }, 'gsOwq': function (_0x39eec2, _0x1a5228, _0x19884b, _0x4b2186, _0x32ab39, _0x1395df) { return _0x39eec2(_0x1a5228, _0x19884b, _0x4b2186, _0x32ab39, _0x1395df); }, 'dYnrU': function (_0x349385, _0x48ab16) { return _0x349385 < _0x48ab16; }, 'TpaDD': function (_0x1e8df4, _0x302315) { return _0x1e8df4(_0x302315); } }, _0x1b704b = _0x394d50["slice"]();
51
+ for (let _0x2b0e2a = 0; _0x2b0e2a < _0x134952;) {
52
+ if (_0x5995c3["jEcqb"] !== "KJLmG") {
53
+ _0x5995c3["QNwIH"](quarter, _0x1b704b, 0, 4, 8, 12), _0x5995c3["QNwIH"](quarter, _0x1b704b, 1, 5, 9, 13), quarter(_0x1b704b, 2, 6, 10, 14), quarter(_0x1b704b, 3, 7, 11, 15);
54
+ if (_0x5995c3["zIpWr"](++_0x2b0e2a, _0x134952))
55
+ break;
56
+ _0x5995c3["KsqpY"](quarter, _0x1b704b, 0, 5, 10, 15), quarter(_0x1b704b, 1, 6, 11, 12), _0x5995c3["KsqpY"](quarter, _0x1b704b, 2, 7, 12, 13), _0x5995c3["gsOwq"](quarter, _0x1b704b, 3, 4, 13, 14), ++_0x2b0e2a;
57
+ }
58
+ else {
59
+ const _0x39b236 = _0x4a5813["now"]();
60
+ return [_0x1ed987[44], _0x25b170[74], _0x24f952[10], _0x45c9a1[62], _0x3377e5[42], _0x1ee0e7[17], _0xd4eb83[2], _0x519e72[21], _0xcb63e1[3], _0x307155[70], _0x283b6c[50], _0x277c9e[32], _0xa8d840[0] & _0x39b236, _0x358802["randomInt"](_0x473cb0[77]), _0x57f605["randomInt"](_0x48d221[77]), _0x35ec16["randomInt"](_0x1c0240[77])];
61
+ }
62
+ }
63
+ for (let _0x51f2f1 = 0; _0x5995c3["dYnrU"](_0x51f2f1, 16); _0x51f2f1++)
64
+ _0x1b704b[_0x51f2f1] = _0x5995c3["TpaDD"](u32, _0x1b704b[_0x51f2f1] + _0x394d50[_0x51f2f1]);
65
+ return _0x1b704b;
66
+ }
67
+ const bumpCounter = _0x53d1da => { const _0x3c64ea = { 'bJNGQ': function (_0x20706d, _0x576d14) { return _0x20706d(_0x576d14); }, 'ktrsp': function (_0x1024c3, _0x20e00a) { return _0x1024c3 + _0x20e00a; } }; _0x53d1da[12] = _0x3c64ea["bJNGQ"](u32, _0x3c64ea["ktrsp"](_0x53d1da[12], 1)); };
68
+ function rand() { const _0x92ee2d = { 'MFwnz': function (_0x7211cf, _0xc4ed0e, _0x47e671) { return _0x7211cf(_0xc4ed0e, _0x47e671); }, 'jefok': function (_0x24e979, _0x5ae9ba) { return _0x24e979 >>> _0x5ae9ba; }, 'qkpzy': function (_0x143183, _0x2392ee) { return _0x143183 + _0x2392ee; }, 'OwSnW': function (_0x2d9cc3, _0x173e45) { return _0x2d9cc3 / _0x173e45; }, 'OznLd': function (_0x5efd6c, _0x17ec1e) { return _0x5efd6c + _0x17ec1e; }, 'CIKyS': function (_0x11fd36, _0x144270) { return _0x11fd36 * _0x144270; }, 'IDVKW': function (_0x278a2d, _0x2e0ce4) { return _0x278a2d ** _0x2e0ce4; } }, _0x5a8573 = _0x92ee2d["MFwnz"](chachaBlock, kt, 8), _0x59fa63 = _0x5a8573[St], _0x385ac9 = _0x92ee2d["jefok"](_0x5a8573[_0x92ee2d["qkpzy"](St, 8)] & 4294967280, 11); return St === 7 ? (bumpCounter(kt), St = 0) : ++St, _0x92ee2d["OwSnW"](_0x92ee2d["OznLd"](_0x59fa63, _0x92ee2d["CIKyS"](4294967296, _0x385ac9)), _0x92ee2d["IDVKW"](2, 53)); }
69
+ const numToBytes = _0x4c04c9 => _0x4c04c9 < 65025 ? [_0x4c04c9 >> 8 & 255, _0x4c04c9 & 255] : [_0x4c04c9 >> 24 & 255, _0x4c04c9 >> 16 & 255, _0x4c04c9 >> 8 & 255, _0x4c04c9 & 255];
70
+ const beIntFromStr = _0x25722c => {
71
+ const _0x4ffdbf = {};
72
+ _0x4ffdbf["LyrUQ"] = "utf8", _0x4ffdbf["EHKJc"] = function (_0x591931, _0x2904f8) { return _0x591931 << _0x2904f8; }, _0x4ffdbf["tmhEM"] = function (_0x566536, _0x1a3446) { return _0x566536 >>> _0x1a3446; };
73
+ const _0x1d7475 = _0x4ffdbf, _0x15f3cc = Buffer["from"](_0x25722c, _0x1d7475["LyrUQ"])["subarray"](0, 4);
74
+ let _0x353689 = 0;
75
+ for (const _0x224a4e of _0x15f3cc)
76
+ _0x353689 = _0x1d7475["EHKJc"](_0x353689, 8) | _0x224a4e;
77
+ return _0x1d7475["tmhEM"](_0x353689, 0);
78
+ };
79
+ function encryptChaCha(_0x3a2084, _0x1c8166, _0x37ac8d) {
80
+ const _0x249b51 = { 'Tvmei': function (_0x363ec9, _0x266287) { return _0x363ec9 * _0x266287; }, 'pTqDA': function (_0xba1a09, _0xa950d7) { return _0xba1a09 + _0xa950d7; }, 'fVVvA': function (_0x3a64c9, _0x506933) { return _0x3a64c9 >> _0x506933; }, 'eWEAC': function (_0x395335, _0x461955) { return _0x395335 + _0x461955; }, 'rpLBW': function (_0x315a68, _0x137358) { return _0x315a68(_0x137358); }, 'XscWQ': function (_0x44437f, _0x3226af) { return _0x44437f + _0x3226af; }, 'UJrEc': function (_0x1bb830, _0x2d849d) { return _0x1bb830(_0x2d849d); }, 'GXPus': function (_0x190707, _0x169cb5, _0x35060e) { return _0x190707(_0x169cb5, _0x35060e); }, 'WwnZd': function (_0x4deec4, _0x2e7e60) { return _0x4deec4 ^ _0x2e7e60; }, 'qYBNF': function (_0x30855b, _0x2fd875, _0x1532cf) { return _0x30855b(_0x2fd875, _0x1532cf); }, 'QRQbX': function (_0x378b02, _0x2a40ff) { return _0x378b02 ^ _0x2a40ff; }, 'dTpGD': function (_0x5c0347, _0x57fe9b, _0x79baa2) { return _0x5c0347(_0x57fe9b, _0x79baa2); }, 'ZvAfs': function (_0x38a9d8, _0x15ac01) { return _0x38a9d8 ^ _0x15ac01; }, 'SFKCs': function (_0x272965, _0x411f4f) { return _0x272965 + _0x411f4f; }, 'YOSXJ': function (_0x230d16, _0x4a6126) { return _0x230d16 % _0x4a6126; }, 'gEttJ': function (_0x2df6ad, _0x3b3925) { return _0x2df6ad / _0x3b3925; }, 'TCRcm': "OUuHU", 'nzGpK': function (_0x166def, _0x37078d) { return _0x166def | _0x37078d; }, 'JfoQz': function (_0x882d54, _0x4a6ab9) { return _0x882d54 | _0x4a6ab9; }, 'qUyER': function (_0x3ebdcb, _0x3ad46e) { return _0x3ebdcb << _0x3ad46e; }, 'urmyk': function (_0x2cdb90, _0x3a1ec5) { return _0x2cdb90 << _0x3a1ec5; }, 'WMBEY': function (_0x2737e9, _0x12a901) { return _0x2737e9 < _0x12a901; }, 'cKqqD': function (_0x358aae, _0x245766) { return _0x358aae << _0x245766; }, 'lbGrU': function (_0x321e1d, _0x104f57) { return _0x321e1d < _0x104f57; }, 'ZTMtz': function (_0x33367f, _0x536522, _0x1d631e) { return _0x33367f(_0x536522, _0x1d631e); }, 'eOxrU': function (_0x5d1b9b, _0x1e7c6e) { return _0x5d1b9b(_0x1e7c6e); }, 'ZXRQY': function (_0x508e6c, _0x2e54d1) { return _0x508e6c - _0x2e54d1; }, 'TfeeH': function (_0x3fd9f7, _0x5999f4, _0x1ceeb4) { return _0x3fd9f7(_0x5999f4, _0x1ceeb4); }, 'vuvDF': function (_0x93dc6, _0x63503a) { return _0x93dc6 & _0x63503a; }, 'MKhkw': function (_0x31d081, _0x5dee3d) { return _0x31d081 + _0x5dee3d; }, 'xQrwB': function (_0x30af45, _0x2d23b0) { return _0x30af45 + _0x2d23b0; }, 'LPzdD': function (_0x42f753, _0x2e1ebb) { return _0x42f753 >> _0x2e1ebb; }, 'cYlvB': "dbZns", 'jwrCi': function (_0x562d91, _0x1cc2a0) { return _0x562d91 & _0x1cc2a0; } }, _0x58e1bb = Math["floor"](_0x37ac8d["length"] / (4)), _0x203865 = _0x249b51["YOSXJ"](_0x37ac8d["length"], 4), _0x38c786 = new Uint32Array(Math["ceil"](_0x249b51["gEttJ"](_0x37ac8d["length"], 4)));
81
+ for (let _0x13a1ae = 0; _0x13a1ae < _0x58e1bb; _0x13a1ae++) {
82
+ if (_0x249b51["TCRcm"] === "OUuHU") {
83
+ const _0x5c9e46 = _0x249b51["Tvmei"](4, _0x13a1ae);
84
+ _0x38c786[_0x13a1ae] = _0x249b51["nzGpK"](_0x249b51["nzGpK"](_0x249b51["JfoQz"](_0x37ac8d[_0x5c9e46], _0x249b51["qUyER"](_0x37ac8d[_0x249b51["XscWQ"](_0x5c9e46, 1)], 8)), _0x37ac8d[_0x5c9e46 + (2)] << 16), _0x249b51["urmyk"](_0x37ac8d[_0x5c9e46 + (3)], 24));
85
+ }
86
+ else {
87
+ const _0x2f0e39 = _0x31229e[_0xfb2aa8], _0x1a855a = _0x249b51["Tvmei"](4, _0x2f64ee);
88
+ for (let _0x977af7 = 0; _0x977af7 < _0x3b84d0; _0x977af7++)
89
+ _0x53c24a[_0x249b51["pTqDA"](_0x1a855a, _0x977af7)] = _0x249b51["fVVvA"](_0x2f0e39, _0x249b51["Tvmei"](8, _0x977af7)) & 255;
90
+ }
91
+ }
92
+ if (_0x203865) {
93
+ let _0x57d468 = 0, _0x3e38b5 = (4) * _0x58e1bb;
94
+ for (let _0x2c3b4d = 0; _0x249b51["WMBEY"](_0x2c3b4d, _0x203865); _0x2c3b4d++)
95
+ _0x57d468 |= _0x249b51["cKqqD"](_0x37ac8d[_0x249b51["eWEAC"](_0x3e38b5, _0x2c3b4d)], _0x249b51["Tvmei"](8, _0x2c3b4d));
96
+ _0x38c786[_0x58e1bb] = _0x57d468;
97
+ }
98
+ let _0x346ebd = 0;
99
+ const _0x414094 = _0x3a2084["slice"]();
100
+ while (_0x249b51["lbGrU"](_0x346ebd + (16), _0x38c786["length"])) {
101
+ const _0x2ddd86 = _0x249b51["ZTMtz"](chachaBlock, _0x414094, _0x1c8166);
102
+ _0x249b51["eOxrU"](bumpCounter, _0x414094);
103
+ for (let _0x458077 = 0; _0x249b51["WMBEY"](_0x458077, 16); _0x458077++)
104
+ _0x38c786[_0x249b51["pTqDA"](_0x346ebd, _0x458077)] ^= _0x2ddd86[_0x458077];
105
+ _0x346ebd += 16;
106
+ }
107
+ const _0x475ae1 = _0x249b51["ZXRQY"](_0x38c786["length"], _0x346ebd), _0x5ec276 = _0x249b51["TfeeH"](chachaBlock, _0x414094, _0x1c8166);
108
+ for (let _0x98072 = 0; _0x249b51["WMBEY"](_0x98072, _0x475ae1); _0x98072++)
109
+ _0x38c786[_0x249b51["XscWQ"](_0x346ebd, _0x98072)] ^= _0x5ec276[_0x98072];
110
+ for (let _0x192045 = 0; _0x192045 < _0x58e1bb; _0x192045++) {
111
+ const _0xee3c2a = _0x38c786[_0x192045], _0x6b886a = _0x249b51["Tvmei"](4, _0x192045);
112
+ _0x37ac8d[_0x6b886a] = _0x249b51["vuvDF"](_0xee3c2a, 255), _0x37ac8d[_0x249b51["MKhkw"](_0x6b886a, 1)] = _0x249b51["vuvDF"](_0xee3c2a >> 8, 255), _0x37ac8d[_0x249b51["xQrwB"](_0x6b886a, 2)] = _0x249b51["vuvDF"](_0x249b51["LPzdD"](_0xee3c2a, 16), 255), _0x37ac8d[_0x249b51["eWEAC"](_0x6b886a, 3)] = _0x249b51["vuvDF"](_0xee3c2a >> 24, 255);
113
+ }
114
+ if (_0x203865) {
115
+ if (_0x249b51["cYlvB"] === "dbZns") {
116
+ const _0x3d994e = _0x38c786[_0x58e1bb], _0x5aa09e = _0x249b51["Tvmei"](4, _0x58e1bb);
117
+ for (let _0x554716 = 0; _0x249b51["lbGrU"](_0x554716, _0x203865); _0x554716++)
118
+ _0x37ac8d[_0x249b51["MKhkw"](_0x5aa09e, _0x554716)] = _0x249b51["jwrCi"](_0x3d994e >> _0x249b51["Tvmei"](8, _0x554716), 255);
119
+ }
120
+ else {
121
+ const _0x230d89 = ("1|6|2|3|0|5|7|4")["split"]('|');
122
+ let _0x5b5db9 = 0;
123
+ while (!![]) {
124
+ switch (_0x230d89[_0x5b5db9++]) {
125
+ case '0':
126
+ _0x5457e8[_0x229e7d] = _0x24257b(_0x249b51["eWEAC"](_0x4a6a06[_0x147c0b], _0x1df11c[_0x363b62]));
127
+ continue;
128
+ case '1':
129
+ _0x26326f[_0x1074d1] = _0x249b51["rpLBW"](_0x373f88, _0x249b51["XscWQ"](_0x5bec7a[_0x2fcc03], _0x44b024[_0x7adb52]));
130
+ continue;
131
+ case '2':
132
+ _0x9c3a61[_0x2e40ae] = _0x249b51["UJrEc"](_0x41beb8, _0x249b51["eWEAC"](_0x2b8220[_0x45310a], _0x1c8346[_0x37b59b]));
133
+ continue;
134
+ case '3':
135
+ _0x40bdad[_0x2b1f3d] = _0x249b51["GXPus"](_0x5cbf00, _0x249b51["WwnZd"](_0xaea170[_0x3a2aba], _0x217818[_0x5a31c9]), 12);
136
+ continue;
137
+ case '4':
138
+ _0x4443d5[_0x34edfd] = _0x249b51["GXPus"](_0x3070df, _0x249b51["WwnZd"](_0x51fe1e[_0x569b35], _0x181ea2[_0x2f5458]), 7);
139
+ continue;
140
+ case '5':
141
+ _0x4d6fc5[_0x14ebfa] = _0x249b51["qYBNF"](_0x4cae6c, _0x249b51["QRQbX"](_0x556dba[_0x45fe0f], _0x1aaa92[_0x2af7ae]), 8);
142
+ continue;
143
+ case '6':
144
+ _0x4f5652[_0x55eeb2] = _0x249b51["dTpGD"](_0x4ccad2, _0x249b51["ZvAfs"](_0x3158b4[_0x1d51b6], _0x134170[_0x65934]), 16);
145
+ continue;
146
+ case '7':
147
+ _0x172f8a[_0x1aeeef] = _0x580c0f(_0x249b51["SFKCs"](_0x41683f[_0x3659e3], _0x12cc1b[_0x4a1dee]));
148
+ continue;
149
+ }
150
+ break;
151
+ }
152
+ }
153
+ }
154
+ }
155
+ function Ab22(_0x501163, _0x58db1c, _0x461937) { const _0x1fec47 = { 'SzMoI': function (_0x5c0f94, _0x2beedf, _0x283521, _0x5a6924) { return _0x5c0f94(_0x2beedf, _0x283521, _0x5a6924); } }, _0x5e660c = Ot["concat"](_0x501163), _0x558626 = Array["from"](_0x461937, _0x321727 => _0x321727["charCodeAt"](0)); return _0x1fec47["SzMoI"](encryptChaCha, _0x5e660c, _0x58db1c, _0x558626), String["fromCharCode"](..._0x558626); }
156
+ function encrypt(_0xca229b, _0x1ba4cd, _0xf9be7e, _0x467d24 = 0, _0x3022ce = "5.1.1", _0x527b29 = Date["now"]()) {
157
+ const _0x9884bd = { 'PehdN': function (_0x5eeb92, _0x336a3c) { return _0x5eeb92 * _0x336a3c; }, 'DSUBL': function (_0x23b105, _0x544e76) { return _0x23b105 & _0x544e76; }, 'DNoDs': function (_0x4de355, _0x3359a9) { return _0x4de355 + _0x3359a9; }, 'XAEMU': function (_0x50344c, _0x288b1e) { return _0x50344c & _0x288b1e; }, 'gpJda': function (_0x5ceb8d, _0x54777e) { return _0x5ceb8d >> _0x54777e; }, 'cPuMA': function (_0x1ac29c, _0x320d76) { return _0x1ac29c + _0x320d76; }, 'pDJlX': function (_0x45ecaa, _0x1485d1) { return _0x45ecaa & _0x1485d1; }, 'RLDco': function (_0x20fd0f, _0x22ca40) { return _0x20fd0f < _0x22ca40; }, 'LmEmr': function (_0x243093, _0x646f40) { return _0x243093 << _0x646f40; }, 'xBBbE': function (_0x2ef0d2, _0x451567) { return _0x2ef0d2 * _0x451567; }, 'ifjwU': function (_0x1f5b2d, _0x250555) { return _0x1f5b2d | _0x250555; }, 'fhxzg': function (_0x1ceca1, _0x5cdc96) { return _0x1ceca1 | _0x5cdc96; }, 'dKgIx': function (_0x542e34, _0x5e9b9b) { return _0x542e34 << _0x5e9b9b; }, 'vOTGj': function (_0x47b1a1, _0x11d1b1) { return _0x47b1a1 + _0x11d1b1; }, 'mjism': function (_0x4e88cd, _0x240f0d) { return _0x4e88cd + _0x240f0d; }, 'ANPyA': "md5", 'WoEWs': "hex", 'uvZXL': function (_0x1580f5, _0x4b6ecb) { return _0x1580f5 % _0x4b6ecb; }, 'ouCkd': function (_0x3a849c, _0x42c7f0) { return _0x3a849c * _0x42c7f0; }, 'jcJWZ': function (_0x1a9127, _0x327c11) { return _0x1a9127 === _0x327c11; }, 'nIfpT': "5.1.1", 'MOuga': function (_0x225edb, _0xa9b06f) { return _0x225edb <= _0xa9b06f; }, 'OCPRE': "EdFIM", 'zmesr': function (_0x270f61, _0x3c2a01) { return _0x270f61 === _0x3c2a01; }, 'MyWDb': function (_0x2fc982, _0x2055d1) { return _0x2fc982(_0x2055d1); }, 'EclSP': function (_0x113a5e, _0x573389) { return _0x113a5e >>> _0x573389; }, 'anhwZ': function (_0x5ec1cf, _0x4eceae) { return _0x5ec1cf !== _0x4eceae; }, 'BhEZU': "5.1.0", 'weaYp': function (_0x1f03e9, _0x268df1) { return _0x1f03e9 === _0x268df1; }, 'qOWmB': "IcxVL", 'BvEqj': function (_0x2ae085, _0x346376) { return _0x2ae085 === _0x346376; }, 'twmgq': function (_0x2e5de2, _0x2b5a7e) { return _0x2e5de2 >>> _0x2b5a7e; }, 'zwKbM': "number", 'IInwO': "utf8", 'QYEKV': function (_0xee5dc2, _0x26c325) { return _0xee5dc2 >>> _0x26c325; }, 'sRuaQ': function (_0x6c4f0a, _0x2d35cb) { return _0x6c4f0a & _0x2d35cb; }, 'LLNrO': function (_0x30e2d8, _0xb59216) { return _0x30e2d8 & _0xb59216; }, 'YOlBW': function (_0x192079, _0x43ef27) { return _0x192079 & _0x43ef27; }, 'jMRBV': function (_0x91b1d3, _0x5dff33) { return _0x91b1d3 >>> _0x5dff33; }, 'FVXBV': function (_0xe69316, _0xb2a39d) { return _0xe69316 % _0xb2a39d; }, 'WnSlR': function (_0x1bdde5, _0x2cfa4c) { return _0x1bdde5 + _0x2cfa4c; }, 'fKTLn': function (_0x2ea064, _0x30ef6e) { return _0x2ea064 ^ _0x30ef6e; }, 'tjmqZ': "u09tbS3UvgDEe6r-ZVMXzLpsAohTn7mdINQlW412GqBjfYiyk8JORCF5/xKHwacP=", 'esdxo': function (_0x49027c, _0x33c2a2) { return _0x49027c * _0x33c2a2; }, 'gsfDT': function (_0x10b385, _0x5c979f) { return _0x10b385 / _0x5c979f; }, 'OFGfa': function (_0x277ba9, _0x256372) { return _0x277ba9 < _0x256372; }, 'fMlXq': "IVwmC", 'bQQbf': function (_0x134513, _0x43fd42) { return _0x134513 << _0x43fd42; }, 'xEQEk': function (_0x1974f6, _0x389064) { return _0x1974f6 + _0x389064; }, 'yGOnf': function (_0xbc2069, _0x3d028c) { return _0xbc2069 & _0x3d028c; }, 'VVRyJ': function (_0x382c0f, _0x50e2bc) { return _0x382c0f >> _0x50e2bc; }, 'wzUYD': function (_0xc5b6b, _0x255175) { return _0xc5b6b & _0x255175; }, 'aTxHg': function (_0x535ec1, _0xb19660) { return _0x535ec1 >> _0xb19660; }, 'Bltxw': function (_0x223a93, _0x449924) { return _0x223a93 & _0x449924; } }, _0x374bd0 = new Map();
158
+ _0x374bd0["set"](1, 1), _0x374bd0["set"](2, _0x467d24), _0x374bd0["set"](3, crypto["createHash"](_0x9884bd["ANPyA"])["update"](_0xca229b)["digest"]("hex")), _0x374bd0["set"](4, crypto["createHash"](_0x9884bd["ANPyA"])["update"](_0x1ba4cd)["digest"]("hex")), _0x374bd0["set"](5, crypto["createHash"](_0x9884bd["ANPyA"])["update"](_0xf9be7e)["digest"](_0x9884bd["WoEWs"])), _0x374bd0["set"](6, Math["floor"](_0x527b29 / (1000))), _0x374bd0["set"](7, 1508145731), _0x374bd0["set"](8, _0x9884bd["uvZXL"](_0x9884bd["ouCkd"](_0x527b29, 1000), 2147483648)), _0x374bd0["set"](9, _0x3022ce);
159
+ if (_0x9884bd["jcJWZ"](_0x3022ce, _0x9884bd["nIfpT"])) {
160
+ _0x374bd0["set"](10, "1.0.0.314"), _0x374bd0["set"](11, 1);
161
+ let _0x345d82 = 0;
162
+ for (let _0x281e2d = 1; _0x9884bd["MOuga"](_0x281e2d, 11); _0x281e2d++) {
163
+ if ("BMfXJ" === _0x9884bd["OCPRE"]) {
164
+ const _0x5cd8f9 = _0x58eb34[_0x20520b], _0x62b0f1 = _0x9884bd["PehdN"](4, _0x397708);
165
+ _0x2914b6[_0x62b0f1] = _0x9884bd["DSUBL"](_0x5cd8f9, 255), _0x443dc0[_0x9884bd["DNoDs"](_0x62b0f1, 1)] = _0x9884bd["XAEMU"](_0x9884bd["gpJda"](_0x5cd8f9, 8), 255), _0x4fe60e[_0x9884bd["cPuMA"](_0x62b0f1, 2)] = _0x9884bd["pDJlX"](_0x9884bd["gpJda"](_0x5cd8f9, 16), 255), _0x5b1103[_0x62b0f1 + (3)] = _0x9884bd["gpJda"](_0x5cd8f9, 24) & 255;
166
+ }
167
+ else {
168
+ const _0x1c7028 = _0x374bd0["get"](_0x281e2d), _0xafa08e = _0x9884bd["zmesr"](typeof _0x1c7028, "number") ? _0x1c7028 : _0x9884bd["MyWDb"](beIntFromStr, _0x1c7028);
169
+ _0x345d82 ^= _0xafa08e;
170
+ }
171
+ }
172
+ _0x374bd0["set"](12, _0x9884bd["EclSP"](_0x345d82, 0));
173
+ }
174
+ else {
175
+ if (_0x9884bd["anhwZ"](_0x3022ce, _0x9884bd["BhEZU"])) {
176
+ if (_0x9884bd["weaYp"](_0x9884bd["qOWmB"], _0x9884bd["qOWmB"]))
177
+ throw new Error("Unsupported version: " + _0x3022ce);
178
+ else {
179
+ let _0x53a52b = 0, _0x2ed97f = _0x9884bd["PehdN"](4, _0xd87d5c);
180
+ for (let _0x300826 = 0; _0x9884bd["RLDco"](_0x300826, _0x572472); _0x300826++)
181
+ _0x53a52b |= _0x9884bd["LmEmr"](_0x57a67b[_0x9884bd["cPuMA"](_0x2ed97f, _0x300826)], (8) * _0x300826);
182
+ _0x344dec[_0x4bdbd8] = _0x53a52b;
183
+ }
184
+ }
185
+ }
186
+ let _0x417774 = 0;
187
+ for (let _0x38daa = 1; _0x38daa <= _0x374bd0["size"]; _0x38daa++) {
188
+ const _0x35caf8 = _0x374bd0["get"](_0x38daa);
189
+ if (_0x9884bd["BvEqj"](typeof _0x35caf8, "number"))
190
+ _0x417774 ^= _0x35caf8;
191
+ }
192
+ _0x374bd0["set"](0, _0x9884bd["twmgq"](_0x417774, 0));
193
+ const _0x35d662 = [];
194
+ _0x35d662["push"](_0x374bd0["size"]);
195
+ for (const [_0x170a5a, _0x28cdca] of _0x374bd0) {
196
+ _0x35d662["push"](_0x170a5a);
197
+ const _0x69979c = _0x9884bd["jcJWZ"](typeof _0x28cdca, _0x9884bd["zwKbM"]) ? _0x9884bd["MyWDb"](numToBytes, _0x28cdca) : Array["from"](Buffer["from"](_0x28cdca, _0x9884bd["IInwO"]));
198
+ _0x35d662["push"](...numToBytes(_0x69979c["length"])), _0x35d662["push"](..._0x69979c);
199
+ }
200
+ const _0x2f28b9 = String["fromCharCode"](..._0x35d662), _0x22b124 = [], _0x90ea4a = [];
201
+ let _0xe3e3ea = 0;
202
+ for (let _0x3bd87d = 0; _0x3bd87d < 12; _0x3bd87d++) {
203
+ const _0x10660f = rand(), _0x1d0a18 = _0x9884bd["QYEKV"](_0x9884bd["PehdN"](_0x10660f, 4294967296), 0);
204
+ _0x22b124["push"](_0x1d0a18), _0xe3e3ea = _0x9884bd["DSUBL"](_0x9884bd["DNoDs"](_0xe3e3ea, _0x9884bd["sRuaQ"](_0x1d0a18, 15)), 15), _0x90ea4a["push"](_0x9884bd["LLNrO"](_0x1d0a18, 255), _0x9884bd["pDJlX"](_0x9884bd["twmgq"](_0x1d0a18, 8), 255), _0x9884bd["LLNrO"](_0x9884bd["twmgq"](_0x1d0a18, 16), 255), _0x9884bd["YOlBW"](_0x9884bd["jMRBV"](_0x1d0a18, 24), 255));
205
+ }
206
+ const _0x1946ba = _0xe3e3ea + (5), _0x24a258 = Ab22(_0x22b124, _0x1946ba, _0x2f28b9);
207
+ let _0x1ce316 = 0;
208
+ for (const _0x5082a2 of _0x90ea4a)
209
+ _0x1ce316 = _0x9884bd["FVXBV"](_0x1ce316 + _0x5082a2, _0x9884bd["cPuMA"](_0x24a258["length"], 1));
210
+ for (const _0x5379ce of _0x24a258)
211
+ _0x1ce316 = (_0x1ce316 + _0x5379ce["charCodeAt"](0)) % _0x9884bd["cPuMA"](_0x24a258["length"], 1);
212
+ const _0x3593fe = String["fromCharCode"](..._0x90ea4a), _0x2684de = _0x9884bd["WnSlR"](_0x9884bd["DNoDs"](String["fromCharCode"](_0x9884bd["fKTLn"](_0x9884bd["fKTLn"](_0x9884bd["dKgIx"](1, 6), _0x9884bd["LmEmr"](1, 3)), 3) & 255) + _0x24a258["slice"](0, _0x1ce316), _0x3593fe), _0x24a258["slice"](_0x1ce316)), _0x56a553 = _0x9884bd["tjmqZ"], _0x58c17e = [], _0x361c7a = _0x9884bd["esdxo"](Math["floor"](_0x9884bd["gsfDT"](_0x2684de["length"], 3)), 3);
213
+ for (let _0x5b6423 = 0; _0x9884bd["OFGfa"](_0x5b6423, _0x361c7a); _0x5b6423 += 3) {
214
+ if (_0x9884bd["fMlXq"] === "DwIrF") {
215
+ const _0x56c41d = _0x9884bd["xBBbE"](4, _0x3fa5e5);
216
+ _0x5324ab[_0x38874f] = _0x9884bd["ifjwU"](_0x9884bd["fhxzg"](_0x188bf6[_0x56c41d], _0x9884bd["dKgIx"](_0x37b4c4[_0x9884bd["vOTGj"](_0x56c41d, 1)], 8)), _0x9884bd["dKgIx"](_0x511516[_0x9884bd["mjism"](_0x56c41d, 2)], 16)) | _0x9884bd["dKgIx"](_0x49016b[_0x9884bd["cPuMA"](_0x56c41d, 3)], 24);
217
+ }
218
+ else {
219
+ const _0x28df5a = _0x9884bd["ifjwU"](_0x9884bd["bQQbf"](_0x2684de["charCodeAt"](_0x5b6423), 16) | _0x2684de["charCodeAt"](_0x9884bd["xEQEk"](_0x5b6423, 1)) << 8, _0x2684de["charCodeAt"](_0x5b6423 + (2)));
220
+ _0x58c17e["push"](_0x56a553[_0x9884bd["yGOnf"](_0x9884bd["VVRyJ"](_0x28df5a, 18), 63)], _0x56a553[_0x9884bd["sRuaQ"](_0x28df5a >> 12, 63)], _0x56a553[_0x9884bd["wzUYD"](_0x9884bd["aTxHg"](_0x28df5a, 6), 63)], _0x56a553[_0x9884bd["Bltxw"](_0x28df5a, 63)]);
221
+ }
222
+ }
223
+ return _0x58c17e["join"]('');
224
+ }
225
+ module.exports = { encrypt };
@@ -0,0 +1,6 @@
1
+ export interface TikTokSession {
2
+ headers: Record<string, string>;
3
+ params: Record<string, string>;
4
+ cookies: Record<string, string>;
5
+ }
6
+ export declare function parseTikTokSession(value: unknown): TikTokSession;
@@ -0,0 +1,33 @@
1
+ import { object, string } from "./http.js";
2
+ function stringMap(value) {
3
+ if (value === undefined)
4
+ return {};
5
+ const result = {};
6
+ for (const [key, item] of Object.entries(object(value))) {
7
+ if (typeof item !== 'string' && typeof item !== 'number' && typeof item !== 'boolean')
8
+ throw new Error('Invalid TikTok session field');
9
+ result[key] = String(item);
10
+ }
11
+ return result;
12
+ }
13
+ export function parseTikTokSession(value) {
14
+ let input = value;
15
+ if (typeof input === 'string') {
16
+ try {
17
+ input = JSON.parse(input);
18
+ }
19
+ catch {
20
+ throw new Error('Invalid TikTok session JSON');
21
+ }
22
+ }
23
+ const outer = object(input), http = object(outer.http ?? outer);
24
+ const headers = Object.fromEntries(Object.entries(stringMap(http.headers)).map(([key, item]) => [key.toLowerCase(), item]));
25
+ delete headers.host;
26
+ delete headers['content-length'];
27
+ delete headers.connection;
28
+ const cookies = stringMap(http.cookies);
29
+ if (!headers.cookie && Object.keys(cookies).length)
30
+ headers.cookie = Object.entries(cookies).map(([key, item]) => `${key}=${item}`).join('; ');
31
+ string(headers.cookie, 'session cookie');
32
+ return { headers, params: stringMap(http.params), cookies };
33
+ }
@@ -0,0 +1,2 @@
1
+ import type { TikTokSession } from './session.ts';
2
+ export declare function signWebPost(session: TikTokSession, body: string, nowMs: number): string;
@@ -0,0 +1,13 @@
1
+ import { createRequire } from 'node:module';
2
+ import { string } from "./http.js";
3
+ const require = createRequire(import.meta.url);
4
+ const bogus = require('./recovered/x-bogus.cjs');
5
+ const gnarly = require('./recovered/x-gnarly.cjs');
6
+ export function signWebPost(session, body, nowMs) {
7
+ const userAgent = string(session.headers['user-agent'] ?? session.params.browser_version, 'user-agent');
8
+ const query = new URLSearchParams({ app_name: 'tiktok_web', channel: 'tiktok_web', device_platform: 'web',
9
+ tz_name: session.params.tz_name ?? 'Asia/Saigon', aid: '1988', msToken: string(session.params.msToken, 'msToken') });
10
+ query.set('X-Bogus', bogus.encrypt(query.toString(), body, userAgent, Math.floor(nowMs / 1000)));
11
+ query.set('X-Gnarly', gnarly.encrypt(query.toString(), body, userAgent, 0, '5.1.1', nowMs));
12
+ return query.toString();
13
+ }
@@ -0,0 +1,7 @@
1
+ export interface UploadToken {
2
+ accessKeyId: string;
3
+ secretAccessKey: string;
4
+ sessionToken: string;
5
+ currentTime?: number;
6
+ }
7
+ export declare function signVodRequest(url: URL, method: string, body: string, token: UploadToken, now: Date): Record<string, string>;
@@ -0,0 +1,17 @@
1
+ import { createHash, createHmac } from 'node:crypto';
2
+ const hash = (data) => createHash('sha256').update(data).digest('hex');
3
+ const hmac = (key, value) => createHmac('sha256', key).update(value).digest();
4
+ const encode = (s) => encodeURIComponent(s).replace(/[!'()*]/g, c => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);
5
+ export function signVodRequest(url, method, body, token, now) {
6
+ const date = now.toISOString().replace(/[:-]|\.\d{3}/g, '');
7
+ const headers = { 'x-amz-date': date, 'x-amz-security-token': token.sessionToken };
8
+ if (body)
9
+ headers['x-amz-content-sha256'] = hash(body);
10
+ const keys = Object.keys(headers).sort();
11
+ const query = [...url.searchParams].sort(([a, av], [b, bv]) => a < b ? -1 : a > b ? 1 : av < bv ? -1 : av > bv ? 1 : 0).map(([key, value]) => `${encode(key)}=${encode(value)}`).join('&');
12
+ const canonical = [method, url.pathname, query, keys.map(key => `${key}:${headers[key]}\n`).join(''), keys.join(';'), hash(body)].join('\n');
13
+ const scope = `${date.slice(0, 8)}/ap-singapore-1/vod/aws4_request`;
14
+ const key = hmac(hmac(hmac(hmac(`AWS4${token.secretAccessKey}`, date.slice(0, 8)), 'ap-singapore-1'), 'vod'), 'aws4_request');
15
+ headers.authorization = `AWS4-HMAC-SHA256 Credential=${token.accessKeyId}/${scope}, SignedHeaders=${keys.join(';')}, Signature=${hmac(key, ['AWS4-HMAC-SHA256', date, scope, hash(canonical)].join('\n')).toString('hex')}`;
16
+ return headers;
17
+ }
@@ -0,0 +1,12 @@
1
+ import type { JsonObject } from './http.ts';
2
+ import type { UploadToken } from './vod-signature.ts';
3
+ import type { UploadedVideo } from './post-body.ts';
4
+ type Request = (url: string, init: RequestInit) => Promise<JsonObject>;
5
+ export declare function uploadVodVideo(input: {
6
+ path: string;
7
+ userId: string;
8
+ token: UploadToken;
9
+ request: Request;
10
+ now: () => number;
11
+ }): Promise<UploadedVideo>;
12
+ export {};
@@ -0,0 +1,72 @@
1
+ import { open } from 'node:fs/promises';
2
+ import { object, string } from "./http.js";
3
+ import { signVodRequest } from "./vod-signature.js";
4
+ function crc32(bytes) {
5
+ let crc = 0xffffffff;
6
+ for (const byte of bytes) {
7
+ crc ^= byte;
8
+ for (let bit = 0; bit < 8; bit++)
9
+ crc = (crc >>> 1) ^ (crc & 1 ? 0xedb88320 : 0);
10
+ }
11
+ return ((crc ^ 0xffffffff) >>> 0).toString(16).padStart(8, '0');
12
+ }
13
+ function first(value) { if (!Array.isArray(value) || !value[0])
14
+ throw new Error('Missing upload result'); return object(value[0]); }
15
+ export async function uploadVodVideo(input) {
16
+ const file = await open(input.path, 'r');
17
+ try {
18
+ const stats = await file.stat();
19
+ if (!stats.isFile() || stats.size < 1)
20
+ throw new Error('Video must be a nonempty file');
21
+ async function vod(action, body) {
22
+ const url = new URL('https://www.tiktok.com/top/v1');
23
+ url.search = new URLSearchParams({ Action: action, Version: '2020-11-19', SpaceName: 'tiktok',
24
+ ...(body ? {} : { FileType: 'video', IsInner: '1', FileSize: String(stats.size) }) }).toString();
25
+ const serialized = body ? JSON.stringify(body) : '';
26
+ const time = input.token.currentTime === undefined ? input.now() : input.token.currentTime * 1000;
27
+ return input.request(url.toString(), { method: body ? 'POST' : 'GET', headers: signVodRequest(url, body ? 'POST' : 'GET', serialized, input.token, new Date(time)), ...(body ? { body: serialized } : {}) });
28
+ }
29
+ const applied = await vod('ApplyUploadInner');
30
+ const node = first(object(object(applied.Result).InnerUploadAddress).UploadNodes);
31
+ const store = first(node.StoreInfos);
32
+ const host = new URL(`https://${string(node.UploadHost, 'UploadHost')}`);
33
+ // Session cookies belong to TikTok, never to the separate upload host.
34
+ if (!host.hostname.endsWith('.tiktok.com') && !host.hostname.endsWith('.tiktokv.com') && !host.hostname.endsWith('.byteoversea.com') && !host.hostname.endsWith('.ibyteimg.com'))
35
+ throw new Error('Unsupported upload host');
36
+ const uploadUrl = new URL(`/upload/v1/${string(store.StoreUri, 'StoreUri')}`, host);
37
+ const headers = { Authorization: string(store.Auth, 'upload Auth'), 'X-Storage-U': encodeURIComponent(input.userId) };
38
+ const extra = node.UploadHeader === undefined ? {} : object(node.UploadHeader);
39
+ for (const [key, value] of Object.entries(extra))
40
+ if (typeof value === 'string')
41
+ headers[key] = value;
42
+ const initUrl = new URL(uploadUrl);
43
+ initUrl.search = 'uploadmode=part&phase=init';
44
+ const initialized = await input.request(initUrl.toString(), { method: 'POST', headers });
45
+ const uploadId = string(object(initialized.data).uploadid, 'uploadid');
46
+ const checksums = [];
47
+ const partSizeBytes = 5 * 1024 * 1024;
48
+ for (let offset = 0, part = 1; offset < stats.size; offset += partSizeBytes, part++) {
49
+ const buffer = Buffer.alloc(Math.min(partSizeBytes, stats.size - offset));
50
+ const { bytesRead } = await file.read(buffer, 0, buffer.length, offset);
51
+ if (bytesRead !== buffer.length)
52
+ throw new Error('Video file changed during upload');
53
+ const checksum = crc32(buffer);
54
+ checksums.push(`${part}:${checksum}`);
55
+ const partUrl = new URL(uploadUrl);
56
+ partUrl.search = new URLSearchParams({ uploadid: uploadId, part_number: String(part), phase: 'transfer' }).toString();
57
+ await input.request(partUrl.toString(), { method: 'POST', headers: { ...headers, 'Content-CRC32': checksum, 'Content-Type': 'application/octet-stream' }, body: new Uint8Array(buffer) });
58
+ }
59
+ const finish = new URL(uploadUrl);
60
+ finish.search = new URLSearchParams({ uploadmode: 'part', phase: 'finish', uploadid: uploadId }).toString();
61
+ await input.request(finish.toString(), { method: 'POST', headers, body: checksums.join(',') });
62
+ const committed = object((await vod('CommitUploadInner', { SessionKey: string(node.SessionKey, 'SessionKey'), Functions: [] })).Result);
63
+ const result = first(committed.Results);
64
+ const meta = object(result.VideoMeta);
65
+ if (typeof meta.Width !== 'number' || typeof meta.Height !== 'number')
66
+ throw new Error('Missing video dimensions');
67
+ return { videoId: string(result.Vid, 'Vid'), width: meta.Width, height: meta.Height };
68
+ }
69
+ finally {
70
+ await file.close();
71
+ }
72
+ }
@@ -0,0 +1,29 @@
1
+ import type { HttpTransport } from './http.ts';
2
+ import type { WebPostOptions } from './post-body.ts';
3
+ export declare function createTikTokWebClient(options: {
4
+ session: unknown;
5
+ transport?: HttpTransport;
6
+ now?: () => number;
7
+ timeoutMs?: number;
8
+ carrierRegion?: string;
9
+ }): {
10
+ getShowcaseProducts({ count, offset }?: {
11
+ count?: number;
12
+ offset?: number;
13
+ }): Promise<{
14
+ productId: string;
15
+ title: string;
16
+ raw: import("./http.ts").JsonObject;
17
+ }[]>;
18
+ getUploadToken: () => Promise<{
19
+ currentTime?: number;
20
+ accessKeyId: string;
21
+ secretAccessKey: string;
22
+ sessionToken: string;
23
+ }>;
24
+ publishVideo: (input: WebPostOptions) => Promise<import("./http.ts").JsonObject>;
25
+ uploadVideo(input: Omit<WebPostOptions, "creationId" | "video"> & {
26
+ videoPath: string;
27
+ creationId?: string;
28
+ }): Promise<import("./http.ts").JsonObject>;
29
+ };
@@ -0,0 +1,63 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { createHttp, object, string } from "./http.js";
3
+ import { parseTikTokSession } from "./session.js";
4
+ import { createWebPostBody } from "./post-body.js";
5
+ import { signWebPost } from "./sign-web-request.js";
6
+ import { uploadVodVideo } from "./vod-upload.js";
7
+ export function createTikTokWebClient(options) {
8
+ const session = parseTikTokSession(options.session), request = createHttp(options.transport, options.timeoutMs), now = options.now ?? Date.now;
9
+ const carrierRegion = options.carrierRegion ?? 'TH';
10
+ if (!/^[A-Z]{2}$/.test(carrierRegion))
11
+ throw new Error('Invalid carrierRegion');
12
+ const headers = { ...session.headers, accept: 'application/json, text/plain, */*', referer: 'https://www.tiktok.com/' };
13
+ async function getUploadToken() {
14
+ const url = new URL('https://www.tiktok.com/api/v1/video/upload/auth/');
15
+ url.search = new URLSearchParams({ aid: '1988', msToken: string(session.params.msToken, 'msToken') }).toString();
16
+ const response = await request(url.toString(), { method: 'GET', headers });
17
+ const token = object(response.video_token_v5 ?? response.audio_token_v5);
18
+ return { accessKeyId: string(token.access_key_id, 'access_key_id'), secretAccessKey: string(token.secret_acess_key ?? token.secret_access_key, 'secret_access_key'),
19
+ sessionToken: string(token.session_token, 'session_token'), ...(typeof token.current_time === 'number' ? { currentTime: token.current_time } : {}) };
20
+ }
21
+ async function attachProducts(products) {
22
+ if (!products.length)
23
+ return;
24
+ const url = `https://shop.tiktok.com/aweme/v1/oec/content/creator/products?aid=1180&carrier_region=${carrierRegion}`;
25
+ await request(url, { method: 'OPTIONS', headers });
26
+ await request(url, { method: 'POST', headers: { ...headers, 'content-type': 'application/json' },
27
+ body: JSON.stringify({ add_targets: [5], products: products.map(p => ({ product_id: string(p.productId, 'productId') })) }) });
28
+ }
29
+ async function publishVideo(input) {
30
+ const body = JSON.stringify(createWebPostBody(input));
31
+ const schedule = input.scheduleTimeSeconds ?? 0;
32
+ if (schedule > 0 && schedule < Math.floor(now() / 1000) + 1200)
33
+ throw new Error('Schedule must be at least 20 minutes ahead');
34
+ // Validate/sign before mutating the showcase.
35
+ const query = signWebPost(session, body, now());
36
+ await attachProducts(input.products ?? []);
37
+ return request(`https://www.tiktok.com/tiktok/web/project/post/v1/?${query}`, { method: 'POST',
38
+ headers: { ...headers, 'content-type': 'application/json', origin: 'https://www.tiktok.com' }, body });
39
+ }
40
+ return {
41
+ async getShowcaseProducts({ count = 6, offset = 0 } = {}) {
42
+ if (!Number.isInteger(count) || count < 1 || count > 50 || !Number.isSafeInteger(offset) || offset < 0)
43
+ throw new Error('Invalid pagination');
44
+ const result = await request(`https://shop.tiktok.com/api/v1/streamer_desktop/showcase_product/list?count=${count}&offset=${offset}`, { method: 'GET', headers });
45
+ const products = object(result.data).products;
46
+ if (!Array.isArray(products))
47
+ throw new Error('Missing products array');
48
+ return products.map(value => { const p = object(value); return { productId: string(p.product_id, 'product_id'), title: string(p.title, 'title'), raw: p }; });
49
+ },
50
+ getUploadToken,
51
+ publishVideo,
52
+ async uploadVideo(input) {
53
+ // Validate product anchors/caption/options before sending video bytes.
54
+ createWebPostBody({ ...input, creationId: input.creationId ?? 'validate', video: { videoId: 'validate', width: 1, height: 1 } });
55
+ const schedule = input.scheduleTimeSeconds ?? 0;
56
+ if (schedule > 0 && schedule < Math.floor(now() / 1000) + 1200)
57
+ throw new Error('Schedule must be at least 20 minutes ahead');
58
+ signWebPost(session, '{}', now());
59
+ const video = await uploadVodVideo({ path: input.videoPath, userId: string(session.params.odinId, 'odinId'), token: await getUploadToken(), request, now });
60
+ return publishVideo({ ...input, creationId: input.creationId ?? randomUUID(), video });
61
+ },
62
+ };
63
+ }
package/package.json CHANGED
@@ -1,6 +1,27 @@
1
1
  {
2
2
  "name": "@yourname168/tiktok",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "Experimental direct TikTok web-session/Shop and official Content Posting API clients, with TypeScript types and no runtime dependencies.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "engines": {
8
+ "node": ">=24 <25"
9
+ },
10
+ "publishConfig": {
11
+ "access": "public",
12
+ "registry": "https://registry.npmjs.org/"
13
+ },
14
+ "exports": {
15
+ ".": {
16
+ "types": "./dist/index.d.ts",
17
+ "default": "./dist/index.js"
18
+ }
19
+ },
20
+ "files": [
21
+ "dist",
22
+ "README.md",
23
+ "REVERSE_NOTES.md",
24
+ "THIRD_PARTY_NOTICES.md",
25
+ "LICENSE"
26
+ ]
6
27
  }