@yourname168/tiktok 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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,157 @@
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
+
57
+ ### Publish a photo album
58
+
59
+ ```ts
60
+ await client.publishPhotoAlbum({
61
+ creationId,
62
+ title: '',
63
+ caption: '',
64
+ photos: uploadedPhotos,
65
+ products: [{ productId: 'chosen-product-id', displayName: 'Tên sản phẩm' }],
66
+ productRegistration: 'existing',
67
+ visibility: 'public',
68
+ music: selectedMusic,
69
+ });
70
+ ```
71
+
72
+ Each uploaded photo needs `id`, `uri`, `width` and `height`. Photo file upload
73
+ is outside the library. The optional music metadata contains `id`, `title`,
74
+ `author`, `url` and `endSeconds` from a TikTok sound selected for the post.
75
+ Optional fields are `startSeconds` (defaults to zero) and `album`.
76
+ Use `aiGenerated: true` when applying TikTok's AI-generated label.
77
+ `publishPhotoAlbum()` defaults to private. `publishPrivatePhotoAlbum()` always
78
+ submits private visibility. Both support `coverIndex` with a default of zero.
79
+
80
+ `addShowcaseProducts()` runs the same product registration used by the publish
81
+ methods. Set `productRegistration: 'existing'` for products already registered
82
+ in the account's Showcase. The default is `'add'`. Use the same option on
83
+ `publishVideo()` or `uploadVideo()`.
84
+
85
+ The publish response is TikTok's raw acknowledgement. Check the published item
86
+ for review status, visibility and whether the product anchor renders. Reuse a known
87
+ `creationId` and inspect TikTok before retrying after a timeout.
88
+
89
+ Optional `coverUri` references an already uploaded cover. Uploading a cover file
90
+ is not ported. Scheduling accepts Unix seconds, at least 20 minutes in the future.
91
+ `carrierRegion` defaults to `TH` to match upstream; configure the actual region.
92
+ `transport` and `now` can be injected for tests, controlled networking and clocks.
93
+ A proxy can be implemented in a supplied transport; there is no global proxy state.
94
+
95
+ ## Official Content Posting API client
96
+
97
+ ```ts
98
+ import { createTikTokContentClient, refreshTikTokToken } from '@yourname168/tiktok';
99
+ const client = createTikTokContentClient({ accessToken: process.env.TIKTOK_ACCESS_TOKEN! });
100
+ const profile = await client.getUserProfile();
101
+ // await client.publishVideoFromUrl({
102
+ // videoUrl: 'https://your-verified-domain.example/video.mp4',
103
+ // caption: 'Demo', privacyLevel: 'SELF_ONLY',
104
+ // });
105
+ // await client.getPostStatus('publish-id');
106
+ ```
107
+
108
+ This client uses OAuth tokens and the official API, with no product anchors.
109
+ It ports profile, status, video-from-URL and refresh-token operations. Photo posts,
110
+ file-based official upload and interactive OAuth authorization are not ported.
111
+
112
+ ## Verification and limits
113
+
114
+ - Golden vectors from the original npm code cover both web signatures, VOD SigV4
115
+ and the complete web post body. Signer entropy/time are fixed only in tests.
116
+ - Offline HTTP tests exercise upload/auth → apply → init → transfer → finish →
117
+ commit → attach products → publish; account cookies never go to storage hosts.
118
+ - Live account trials accepted image and video submissions with product anchor
119
+ fields. Album approval and public visibility were observed in TikTok Studio.
120
+ Product-card rendering and playback of the selected sound remain unverified.
121
+ TikTok's web API can change independently of this package.
122
+ - VOD upload currently ports the normal multipart route. Gateway/stream uploads,
123
+ dynamic slice rules, resume, retries, image upload, messaging, triggers, hashtag
124
+ lookup and comments are not ported. Storage hosts are restricted in vod-upload.ts.
125
+ - Header/payload logic is rewritten in TypeScript. X-Bogus is reconstructed as
126
+ readable JavaScript; X-Gnarly is recovered JavaScript with decoded strings and
127
+ some generated local names still present. Neither imports the original package.
128
+
129
+ Run from the repository:
130
+
131
+ ```sh
132
+ pnpm --filter @gateway/tiktok typecheck
133
+ ```
134
+
135
+ Workspace consumers import source, as established by repository conventions.
136
+ For installation outside the monorepo, generate a compiled JS + declaration tarball:
137
+
138
+ ```sh
139
+ pnpm --filter @gateway/tiktok pack:portable /absolute/output/directory
140
+ npm install /absolute/output/directory/gateway-tiktok-0.2.0.tgz
141
+ ```
142
+
143
+ Use this portable tarball instead of packing the TypeScript workspace directly:
144
+ Node 24 does not strip TypeScript inside node_modules.
145
+
146
+ See [REVERSE_NOTES.md](./REVERSE_NOTES.md) for the request map and provenance,
147
+ and [THIRD_PARTY_NOTICES.md](./THIRD_PARTY_NOTICES.md) for attribution.
148
+
149
+ To prepare a public release under the npm account scope:
150
+
151
+ ```sh
152
+ pnpm --filter @gateway/tiktok pack:portable /absolute/output/directory --name @yourname168/tiktok
153
+ npm publish /absolute/output/directory/yourname168-tiktok-0.2.0.tgz --access public
154
+ ```
155
+
156
+ The public tarball excludes tests, session files, npm credentials and workspace
157
+ 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,44 @@
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
+ // TikTok's multipart storage endpoint uses 2000 for successful operations.
37
+ const storageSuccess = new URL(url).pathname.startsWith('/upload/v1/') && data.code === 2000;
38
+ if ((metadata && object(metadata).Error) || (apiError && object(apiError).code !== undefined && object(apiError).code !== 'ok') ||
39
+ (data.status_code !== undefined && data.status_code !== 0) || (data.code !== undefined && data.code !== 0 && !storageSuccess)) {
40
+ throw new Error('TikTok rejected the request');
41
+ }
42
+ return data;
43
+ };
44
+ }
@@ -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 { createPhotoPostBody, createWebPostBody, productAnchors } from './post-body.ts';
5
+ export type { TikTokSession } from './session.ts';
6
+ export type { PhotoAlbumMusic, PhotoPostOptions, PrivatePhotoPostOptions, ProductAnchor, UploadedPhoto, 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 { createPhotoPostBody, createWebPostBody, productAnchors } from "./post-body.js";