@dohaidang/locket_mod.js 0.0.0-stage → 0.0.4

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.
@@ -0,0 +1,162 @@
1
+ const fs = require("fs");
2
+ const { fetchWithTimeout } = require("../http");
3
+
4
+ let sharp = null;
5
+ try { sharp = require("sharp"); } catch (e) { sharp = null; }
6
+
7
+ class UserModule {
8
+ constructor(client) {
9
+ this.client = client;
10
+ }
11
+
12
+ async getProfile(userUid = null) {
13
+ const target = userUid || this.client.session.uid;
14
+ const res = await this.client.postApi("fetchUserV2", { user_uid: target });
15
+ const profile = (res && res.data) ? res.data : res;
16
+
17
+ if (!userUid || userUid === this.client.session.uid) {
18
+ try {
19
+ const token = await this.client.session.getValidToken();
20
+ const lookupUrl = `${this.client.session.constructor.FIREBASE_AUTH_URL}:lookup?key=${this.client.session.constructor.FIREBASE_API_KEY}`;
21
+ const headers = {
22
+ "User-Agent": this.client.device.userAgent,
23
+ "X-Ios-Bundle-Identifier": this.client.device.bundleId,
24
+ "Content-Type": "application/json"
25
+ };
26
+ const fbRes = await fetchWithTimeout(lookupUrl, { method: "POST", headers, body: JSON.stringify({ idToken: token }) }, 30000);
27
+ if (fbRes.status === 200) {
28
+ const fbData = await fbRes.json();
29
+ const fbUsers = fbData.users || [];
30
+ if (fbUsers.length) {
31
+ const fbU = fbUsers[0];
32
+ if (fbU.photoUrl) profile.profile_picture_url = fbU.photoUrl;
33
+ if (fbU.email) profile.email = fbU.email;
34
+ }
35
+ }
36
+ } catch (e) {}
37
+ }
38
+ return profile;
39
+ }
40
+
41
+ async getProfileByUsername(username) {
42
+ const token = await this.client.friends.resolveInviteTokenFromUsername(username);
43
+ if (token) {
44
+ const res = await this.client.friends.fetchUserByInviteToken(token);
45
+ return (res && res.user) ? res.user : res;
46
+ }
47
+ return { error: "User not found or unable to resolve username link" };
48
+ }
49
+
50
+ async updateProfile(kwargs) {
51
+ return this.client.postApi("changeProfileInfo", kwargs);
52
+ }
53
+
54
+ async updateName(firstName, lastName) {
55
+ return this.updateProfile({ first_name: firstName, last_name: lastName });
56
+ }
57
+
58
+ async updateBirthdate(birthdate) {
59
+ return this.updateProfile({ birthdate });
60
+ }
61
+
62
+ async updateAvatar(imageOrUrl) {
63
+ let imageUrl = imageOrUrl;
64
+ if (!(typeof imageOrUrl === "string" && imageOrUrl.startsWith("http"))) {
65
+ imageUrl = await this.uploadAvatar(imageOrUrl);
66
+ }
67
+
68
+ const token = await this.client.session.getValidToken();
69
+ const url = `${this.client.session.constructor.FIREBASE_AUTH_URL}:update?key=${this.client.session.constructor.FIREBASE_API_KEY}`;
70
+ const headers = {
71
+ "User-Agent": this.client.device.userAgent,
72
+ "X-Ios-Bundle-Identifier": this.client.device.bundleId,
73
+ "Content-Type": "application/json"
74
+ };
75
+ const payload = { idToken: token, photoUrl: imageUrl, returnSecureToken: true };
76
+ const res = await fetch(url, { method: "POST", headers, body: JSON.stringify(payload) });
77
+ if (res.status === 200) {
78
+ const data = await res.json();
79
+ this.client.session.idToken = data.idToken || token;
80
+ this.client.session.refreshToken = data.refreshToken || this.client.session.refreshToken;
81
+ this.client.session.save();
82
+ return { status: 200, profile_picture_url: imageUrl, user: data };
83
+ }
84
+ return { status: res.status, profile_picture_url: imageUrl, error: await res.text() };
85
+ }
86
+
87
+ async uploadAvatar(filePathOrBytes) {
88
+ let rawBytes;
89
+ if (typeof filePathOrBytes === "string") {
90
+ rawBytes = fs.readFileSync(filePathOrBytes);
91
+ } else {
92
+ rawBytes = filePathOrBytes;
93
+ }
94
+ let webpBuffer;
95
+ if (sharp) {
96
+ let img = sharp(rawBytes);
97
+ const meta = await img.metadata();
98
+ if (meta.hasAlpha) img = img.toFormat("webp", { quality: 85 });
99
+ else img = img.toFormat("webp", { quality: 85 });
100
+ webpBuffer = await img.toBuffer();
101
+ } else {
102
+ webpBuffer = Buffer.from(rawBytes);
103
+ }
104
+
105
+ const userUid = this.client.session.uid;
106
+ const token = await this.client.session.getValidToken();
107
+ const url = `https://firebasestorage.googleapis.com/v0/b/locket-img/o/users%2F${userUid}%2Fpublic%2Fprofile_pic.webp`;
108
+ const headers = {
109
+ Authorization: `Firebase ${token}`,
110
+ "Content-Type": "image/webp",
111
+ "x-firebase-storage-version": "ios/12.12.1",
112
+ "x-firebase-gmpid": this.client.session.constructor.FIREBASE_APP_ID,
113
+ "User-Agent": `${this.client.device.userAgent} (GTMSUF/1)`
114
+ };
115
+ const res = await fetchWithTimeout(url, { method: "POST", headers, body: webpBuffer }, 30000);
116
+ if (res.status !== 200) throw new Error(`Avatar upload failed (${res.status}): ${await res.text()}`);
117
+ const meta = await res.json();
118
+ const dlToken = meta.downloadTokens || "";
119
+ return `https://firebasestorage.googleapis.com:443/v0/b/locket-img/o/users%2F${userUid}%2Fpublic%2Fprofile_pic.webp?alt=media&token=${dlToken}`;
120
+ }
121
+
122
+ async syncClientData(options = {}) {
123
+ const { pushNotifications = true, autoSync = true, extraData = null } = options;
124
+ let data;
125
+ if (autoSync) {
126
+ data = {
127
+ ios_version: `${this.client.device.appVersion}.${this.client.device.buildNumber}`,
128
+ push_notifications_enabled: pushNotifications
129
+ };
130
+ } else {
131
+ data = { push_notifications_enabled: pushNotifications };
132
+ }
133
+ if (extraData) Object.assign(data, extraData);
134
+ return this.client.postApi("setClientData", { client_data: data });
135
+ }
136
+
137
+ async setNotificationToken(options = {}) {
138
+ const { fcmToken = null, autoFake = true } = options;
139
+ const crypto = require("crypto");
140
+ let token = "";
141
+ if (!autoFake) {
142
+ token = fcmToken || "";
143
+ } else {
144
+ if (fcmToken) {
145
+ token = fcmToken;
146
+ } else {
147
+ const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-";
148
+ let suffix = "";
149
+ for (let i = 0; i < 140; i++) suffix += chars[Math.floor(Math.random() * chars.length)];
150
+ token = `${this.client.device.installationId}:APA91b${suffix}`;
151
+ }
152
+ }
153
+ const payload = {
154
+ app: "locket",
155
+ installation_id: this.client.device.installationId,
156
+ notification_token: token
157
+ };
158
+ return this.client.postApi("setNotificationToken", payload);
159
+ }
160
+ }
161
+
162
+ module.exports = { UserModule };
package/lib/session.js ADDED
@@ -0,0 +1,131 @@
1
+ const fs = require("fs");
2
+ const path = require("path");
3
+ const { AuthenticationError } = require("./exceptions");
4
+ const { DeviceProfile } = require("./device");
5
+ const { fetchWithTimeout } = require("./http");
6
+
7
+ class SessionManager {
8
+ static FIREBASE_API_KEY = "AIzaSyCQngaaXQIfJaH0aS2l7REgIjD7nL431So";
9
+ static FIREBASE_AUTH_URL = "https://identitytoolkit.googleapis.com/v1/accounts";
10
+ static FIREBASE_TOKEN_URL = "https://securetoken.googleapis.com/v1/token";
11
+ static FIREBASE_APP_ID = "1:641029076083:ios:cc8eb46290d69b234fa606";
12
+
13
+ constructor(options = {}) {
14
+ const { sessionPath = "locket.js_session.json", device = null } = options;
15
+ this.sessionPath = sessionPath;
16
+ this.device = device || new DeviceProfile();
17
+ this.uid = null;
18
+ this.email = null;
19
+ this.idToken = null;
20
+ this.refreshToken = null;
21
+ this.expiresAt = 0;
22
+ this.load();
23
+ }
24
+
25
+ load() {
26
+ if (!this.sessionPath || !fs.existsSync(this.sessionPath)) return false;
27
+ try {
28
+ const data = JSON.parse(fs.readFileSync(this.sessionPath, "utf-8"));
29
+ this.uid = data.uid || null;
30
+ this.email = data.email || null;
31
+ this.idToken = data.idToken || null;
32
+ this.refreshToken = data.refreshToken || null;
33
+ this.expiresAt = data.expiresAt || 0;
34
+ if (data.device) this.device = DeviceProfile.fromDict(data.device);
35
+ return true;
36
+ } catch (e) {
37
+ return false;
38
+ }
39
+ }
40
+
41
+ save() {
42
+ if (!this.sessionPath) return;
43
+ const data = {
44
+ uid: this.uid,
45
+ email: this.email,
46
+ idToken: this.idToken,
47
+ refreshToken: this.refreshToken,
48
+ expiresAt: this.expiresAt,
49
+ device: this.device.toDict()
50
+ };
51
+ try {
52
+ const dir = path.dirname(this.sessionPath);
53
+ if (dir && dir !== "." && !fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
54
+ fs.writeFileSync(this.sessionPath, JSON.stringify(data, null, 2), "utf-8");
55
+ try { if (process.platform !== "win32") fs.chmodSync(this.sessionPath, 0o600); } catch (e) {}
56
+ } catch (e) {}
57
+ }
58
+
59
+ async login(email, password) {
60
+ const url = `${this.constructor.FIREBASE_AUTH_URL}:signInWithPassword?key=${this.constructor.FIREBASE_API_KEY}`;
61
+ const headers = this.device.defaultHeaders;
62
+ const payload = { email, password, returnSecureToken: true };
63
+
64
+ let res;
65
+ try {
66
+ res = await fetchWithTimeout(url, { method: "POST", headers, body: JSON.stringify(payload) }, 30000);
67
+ } catch (e) {
68
+ throw new AuthenticationError(`Login request failed: ${e && e.message ? e.message : e}`);
69
+ }
70
+
71
+ let data;
72
+ try { data = await res.json(); } catch (e) { data = {}; }
73
+ if (!res.ok || res.status !== 200) {
74
+ const err = (data && data.error && data.error.message) || (data && data.error) || res.statusText || "Authentication failed";
75
+ throw new AuthenticationError(`Login failed: ${err}`);
76
+ }
77
+ if (!data || !data.idToken) {
78
+ throw new AuthenticationError("Login failed: missing idToken in response");
79
+ }
80
+ this.uid = data.localId;
81
+ this.email = data.email;
82
+ this.idToken = data.idToken;
83
+ this.refreshToken = data.refreshToken;
84
+ this.expiresAt = Date.now() + parseInt(data.expiresIn || 3600, 10) * 1000;
85
+ this.save();
86
+ return data;
87
+ }
88
+
89
+ async refresh() {
90
+ if (!this.refreshToken) throw new AuthenticationError("No refresh token available to renew session!");
91
+ const url = `${this.constructor.FIREBASE_TOKEN_URL}?key=${this.constructor.FIREBASE_API_KEY}`;
92
+ const headers = {
93
+ "User-Agent": this.device.userAgent,
94
+ "X-Ios-Bundle-Identifier": this.device.bundleId,
95
+ "Content-Type": "application/x-www-form-urlencoded"
96
+ };
97
+ const body = new URLSearchParams({ grant_type: "refresh_token", refresh_token: this.refreshToken }).toString();
98
+
99
+ let res;
100
+ try {
101
+ res = await fetchWithTimeout(url, { method: "POST", headers, body }, 30000);
102
+ } catch (e) {
103
+ throw new AuthenticationError(`Token refresh request failed: ${e && e.message ? e.message : e}`);
104
+ }
105
+
106
+ let resData;
107
+ try { resData = await res.json(); } catch (e) { resData = {}; }
108
+ if (!res.ok || res.status !== 200) {
109
+ const err = (resData && resData.error && (resData.error.message || resData.error)) || res.statusText || "Token renewal failed";
110
+ throw new AuthenticationError(`Token refresh failed: ${err}`);
111
+ }
112
+ if (!resData || !resData.id_token) {
113
+ throw new AuthenticationError("Token refresh failed: missing id_token in response");
114
+ }
115
+ this.idToken = resData.id_token;
116
+ this.refreshToken = resData.refresh_token || this.refreshToken;
117
+ this.expiresAt = Date.now() + parseInt(resData.expires_in || 3600, 10) * 1000;
118
+ this.save();
119
+ }
120
+
121
+ async getValidToken() {
122
+ if (!this.idToken) throw new AuthenticationError("Not authenticated! Please call login() first.");
123
+ const nowMs = Date.now();
124
+ if (nowMs >= (this.expiresAt - 60000)) {
125
+ await this.refresh();
126
+ }
127
+ return this.idToken;
128
+ }
129
+ }
130
+
131
+ module.exports = { SessionManager };
package/package.json CHANGED
@@ -1,6 +1,49 @@
1
- {
2
- "name": "@dohaidang/locket_mod.js",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
1
+ {
2
+ "name": "@dohaidang/locket_mod.js",
3
+ "version": "0.0.4",
4
+ "description": "Unofficial Node.js SDK client for Locket Camera",
5
+ "main": "index.js",
6
+ "types": "index.d.ts",
7
+ "files": [
8
+ "index.js",
9
+ "index.d.ts",
10
+ "lib/",
11
+ "caption_presets.json"
12
+ ],
13
+ "publishConfig": {
14
+ "access": "public"
15
+ },
16
+ "scripts": {
17
+ "test": "node --test tests/*.js",
18
+ "lint": "node scripts/lint.js",
19
+ "prepublishOnly": "npm test"
20
+ },
21
+ "keywords": [
22
+ "locket",
23
+ "locket-camera",
24
+ "locket-api",
25
+ "locketjs",
26
+ "ios-client",
27
+ "reverse-engineered"
28
+ ],
29
+ "author": "dohaidang (https://github.com/dohaidang)",
30
+ "homepage": "https://github.com/dohaidang/locket_mod.js#readme",
31
+ "repository": {
32
+ "type": "git",
33
+ "url": "git+https://github.com/dohaidang/locket_mod.js.git"
34
+ },
35
+ "bugs": {
36
+ "url": "https://github.com/dohaidang/locket_mod.js/issues"
37
+ },
38
+ "license": "PolyForm-Noncommercial-1.0.0",
39
+ "dependencies": {
40
+ "sharp": "^0.33.5",
41
+ "ws": "^8.18.0"
42
+ },
43
+ "engines": {
44
+ "node": ">=18"
45
+ },
46
+ "allowScripts": {
47
+ "sharp@0.33.5": true
48
+ }
49
+ }