@pushizo/cli 0.2.0 → 0.4.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/README.md +26 -2
- package/dist/cli.js +96 -1
- package/dist/credential-files.js +317 -0
- package/package.json +3 -3
package/README.md
CHANGED
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
|
|
12
12
|
## English
|
|
13
13
|
|
|
14
|
-
**Pushizo CLI** — The `pushizo` command for scripts and terminals. Lists apps, segments and templates as JSON
|
|
14
|
+
**Pushizo CLI** — The `pushizo` command for scripts and terminals. Lists apps, segments and templates as JSON, sends a notification to subscribed users, and uploads push credentials from a file (`pushizo channels`) without printing their contents. Reads PUSHIZO_API_KEY, PUSHIZO_APP_ID and PUSHIZO_API_URL from the environment; the key is never printed. Node.js 20+, no dependencies.
|
|
15
15
|
|
|
16
16
|
```bash
|
|
17
17
|
npm install -g @pushizo/cli
|
|
@@ -27,7 +27,7 @@ The detailed guide below is in Turkish; code samples are language-neutral. Full
|
|
|
27
27
|
# Pushizo CLI
|
|
28
28
|
|
|
29
29
|
Betikler ve terminal için `pushizo` komutu. App, segment ve şablonları JSON olarak listeler; abone kullanıcılara
|
|
30
|
-
bildirim gönderir. Node.js 20+; bağımlılığı yoktur.
|
|
30
|
+
bildirim gönderir; push anahtarlarını dosyadan yükler ve doğrular. Node.js 20+; bağımlılığı yoktur.
|
|
31
31
|
|
|
32
32
|
## Kurulum
|
|
33
33
|
|
|
@@ -45,6 +45,7 @@ Kurmadan çalıştırmak için: `npx @pushizo/cli --help`.
|
|
|
45
45
|
| `PUSHIZO_API_KEY` | App veya organizasyon API anahtarı (zorunlu). Çıktıya ve hata mesajlarına yazılmaz. |
|
|
46
46
|
| `PUSHIZO_APP_ID` | `segments`, `templates` ve `send` için app kimliği |
|
|
47
47
|
| `PUSHIZO_API_URL` | API adresi (varsayılan `https://api.pushizo.com`; yerelde `http://localhost:4000`) |
|
|
48
|
+
| `PUSHIZO_CREDENTIALS_DIR` | `channels` komutunun anahtar dosyalarını okuyabileceği dizin (varsayılan: bulunduğunuz dizin) |
|
|
48
49
|
|
|
49
50
|
Anahtarı komut satırı argümanı olarak vermeyin; kabuk geçmişine düşer. Ortam değişkeni veya gizli bilgi yöneticisi
|
|
50
51
|
kullanın.
|
|
@@ -56,6 +57,7 @@ pushizo apps # app listesi
|
|
|
56
57
|
pushizo segments # PUSHIZO_APP_ID segmentleri
|
|
57
58
|
pushizo templates # PUSHIZO_APP_ID şablonları
|
|
58
59
|
pushizo send "Başlık" "Gövde metni" # "Subscribed Users" segmentine bildirim (en + tr aynı metin)
|
|
60
|
+
pushizo channels status # kanal başına sağlayıcı ve durum
|
|
59
61
|
pushizo --version
|
|
60
62
|
```
|
|
61
63
|
|
|
@@ -67,6 +69,28 @@ pushizo segments | jq -r '.data[].name'
|
|
|
67
69
|
|
|
68
70
|
Çıkış kodu başarıda `0`, eksik ayar, ağ veya HTTP hatasında `1`'dir; hata ayrıntısı standart hataya yazılır.
|
|
69
71
|
|
|
72
|
+
## Push anahtarını dosyadan yükleme
|
|
73
|
+
|
|
74
|
+
`pushizo channels <kanal>` anahtarı dosyadan okur, yükler ve sağlayıcıya doğrulatır. `admin` kapsamlı anahtar ister.
|
|
75
|
+
|
|
76
|
+
```bash
|
|
77
|
+
pushizo channels apns --key-file AuthKey_ABCDE12345.p8 --team-id TEAM123456 --bundle-id com.ornek.app --environment production
|
|
78
|
+
pushizo channels apns --key-file sertifika.p12 --p12-password-env P12_PAROLA
|
|
79
|
+
pushizo channels fcm --key-file firebase-servis-hesabi.json
|
|
80
|
+
pushizo channels hms --hms-app-id 123456789 --client-secret-env HMS_CLIENT_SECRET
|
|
81
|
+
pushizo channels adm --client-id amzn1.application-oa2-client.x --client-secret-file adm-secret.txt
|
|
82
|
+
pushizo channels wns --package-sid ms-app://s-1-15-2-x --client-secret-file wns-secret.txt
|
|
83
|
+
pushizo channels webpush --subject mailto:siz@ornek.com --site-url https://ornek.com
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
- `.p8` dosyasında Key ID `AuthKey_XXXXXXXXXX.p8` adından okunur; ad farklıysa `--key-id` verin.
|
|
87
|
+
- Sır değeri alan seçenek yoktur: `client_secret` ve `.p12` parolası dosya yolu (`--…-file`) ya da ortam değişkeni
|
|
88
|
+
adı (`--…-env`) ile verilir; böylece kabuk geçmişine düşmez.
|
|
89
|
+
- Dosyalar bulunduğunuz dizinin (ya da `PUSHIZO_CREDENTIALS_DIR`) altında olmalıdır; `..`, mutlak yol ve sembolik bağ
|
|
90
|
+
ile dışarı çıkış reddedilir. Anahtar dosyası en çok 64 KB, metin sırrı 4 KB olabilir.
|
|
91
|
+
- Çıktı yalnız durumdur (`saved`, `ok`, `status`, `error_code`, `hint`, dosya adı, boyutu ve SHA-256 parmak izinin ilk
|
|
92
|
+
12 hanesi). Dosya içeriği ve sırlar yazdırılmaz. Doğrulama geçerse çıkış kodu `0`, geçmezse `1`'dir.
|
|
93
|
+
|
|
70
94
|
Daha geniş kullanım (kullanıcılar, kampanyalar, analitik) için sunucu SDK'larını veya REST API'yi kullanın:
|
|
71
95
|
[docs.pushizo.com/docs/api](https://docs.pushizo.com/docs/api).
|
|
72
96
|
|
package/dist/cli.js
CHANGED
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
* API anahtarı hiçbir çıktıya yazılmaz.
|
|
5
5
|
*/
|
|
6
6
|
import { readFileSync } from 'node:fs';
|
|
7
|
+
import { CredentialError, UPLOAD_CHANNELS, uploadChannelCredentials } from './credential-files.js';
|
|
7
8
|
export const DEFAULT_API_URL = 'https://api.pushizo.com';
|
|
8
9
|
export const VERSION = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
|
|
9
10
|
export const HELP = `Pushizo CLI ${VERSION}
|
|
@@ -13,20 +14,67 @@ Usage:
|
|
|
13
14
|
pushizo segments List segments of PUSHIZO_APP_ID
|
|
14
15
|
pushizo templates List templates of PUSHIZO_APP_ID
|
|
15
16
|
pushizo send "<title>" "<body>" Send a notification to subscribed users of PUSHIZO_APP_ID
|
|
17
|
+
pushizo channels status Provider and status per channel of PUSHIZO_APP_ID
|
|
18
|
+
pushizo channels <apns|fcm|hms|adm|wns|webpush> [options]
|
|
19
|
+
Upload push credentials from a file and validate them
|
|
16
20
|
pushizo --help | --version
|
|
17
21
|
|
|
22
|
+
Channel options (file paths are read by this process; contents are never printed):
|
|
23
|
+
apns --key-file AuthKey_XXXXXXXXXX.p8 --team-id <id> --bundle-id <id> --environment <sandbox|production> [--key-id <id>]
|
|
24
|
+
--key-file cert.p12 [--p12-password-file <path> | --p12-password-env <NAME>] [--bundle-id <id>]
|
|
25
|
+
fcm --key-file service-account.json [--confirm-project-change]
|
|
26
|
+
hms --hms-app-id <id> (--client-secret-file <path> | --client-secret-env <NAME>) [--high-priority]
|
|
27
|
+
adm --client-id <id> (--client-secret-file <path> | --client-secret-env <NAME>)
|
|
28
|
+
wns --package-sid <sid> (--client-secret-file <path> | --client-secret-env <NAME>)
|
|
29
|
+
webpush --subject <mailto:…|https://…> [--site-url <url>]
|
|
30
|
+
[--vapid-public-key <key> (--vapid-private-key-file <path> | --vapid-private-key-env <NAME>)]
|
|
31
|
+
Files must be inside the current directory (or PUSHIZO_CREDENTIALS_DIR). Needs an API key with the admin scope.
|
|
32
|
+
|
|
18
33
|
Environment:
|
|
19
34
|
PUSHIZO_API_KEY App or organization API key (required; never printed)
|
|
20
35
|
PUSHIZO_APP_ID App id for segments, templates and send
|
|
21
36
|
PUSHIZO_API_URL API base URL (default ${DEFAULT_API_URL})
|
|
37
|
+
PUSHIZO_CREDENTIALS_DIR Directory key files may be read from (default: current directory)
|
|
22
38
|
|
|
23
39
|
Türkçe: komutlar aynıdır. apps → app listesi, segments → segmentler, templates → şablonlar,
|
|
24
|
-
send "<başlık>" "<gövde>" → abone kullanıcılara bildirim.
|
|
40
|
+
send "<başlık>" "<gövde>" → abone kullanıcılara bildirim. channels status → kanal durumları;
|
|
41
|
+
channels <kanal> → push anahtarını dosyadan yükler ve doğrular: dosyayı bu süreç okur, içerik ve sırlar çıktıya
|
|
42
|
+
yazılmaz, yalnız durum döner. Dosyalar bulunduğunuz dizinin (ya da PUSHIZO_CREDENTIALS_DIR) altında olmalıdır.
|
|
43
|
+
Ortam değişkenleri yukarıdaki gibidir; anahtar çıktıya yazılmaz.
|
|
25
44
|
|
|
26
45
|
Docs: https://docs.pushizo.com/docs/integrations/cli-sdks
|
|
27
46
|
`;
|
|
28
47
|
class CliError extends Error {
|
|
29
48
|
}
|
|
49
|
+
const CHANNEL_VALUE_FLAGS = [
|
|
50
|
+
'key-file', 'key-id', 'team-id', 'bundle-id', 'environment', 'p12-password-file', 'p12-password-env', 'hms-app-id', 'client-id', 'package-sid',
|
|
51
|
+
'client-secret-file', 'client-secret-env', 'subject', 'site-url', 'vapid-public-key', 'vapid-private-key-file', 'vapid-private-key-env',
|
|
52
|
+
];
|
|
53
|
+
const CHANNEL_BOOLEAN_FLAGS = ['confirm-project-change', 'high-priority'];
|
|
54
|
+
/** `--key-file x --team-id y` → `{ key_file: 'x', team_id: 'y' }`. Sır değeri alan bayrak yoktur (yalnız yol ya da değişken adı). */
|
|
55
|
+
function parseChannelFlags(channel, args) {
|
|
56
|
+
const input = {};
|
|
57
|
+
for (let i = 0; i < args.length; i += 1) {
|
|
58
|
+
const arg = args[i];
|
|
59
|
+
const name = arg.startsWith('--') ? arg.slice(2) : '';
|
|
60
|
+
if (CHANNEL_BOOLEAN_FLAGS.includes(name)) {
|
|
61
|
+
input[name.replaceAll('-', '_')] = true;
|
|
62
|
+
}
|
|
63
|
+
else if (CHANNEL_VALUE_FLAGS.includes(name)) {
|
|
64
|
+
const value = args[i + 1];
|
|
65
|
+
if (value === undefined || value.startsWith('--'))
|
|
66
|
+
throw new CliError(`Missing value · Değer gerekli: ${arg}`);
|
|
67
|
+
input[name.replaceAll('-', '_')] = value;
|
|
68
|
+
i += 1;
|
|
69
|
+
}
|
|
70
|
+
else {
|
|
71
|
+
throw new CliError(`Unknown option · Bilinmeyen seçenek: ${arg}`);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
if (input.environment !== undefined && input.environment !== 'sandbox' && input.environment !== 'production')
|
|
75
|
+
throw new CliError('--environment must be sandbox or production · --environment sandbox ya da production olmalı.');
|
|
76
|
+
return { ...input, channel };
|
|
77
|
+
}
|
|
30
78
|
export async function run(argv, env, io) {
|
|
31
79
|
const [command, ...rest] = argv;
|
|
32
80
|
if (!command || command === 'help' || command === '--help' || command === '-h') {
|
|
@@ -94,12 +142,59 @@ export async function run(argv, env, io) {
|
|
|
94
142
|
}));
|
|
95
143
|
return 0;
|
|
96
144
|
}
|
|
145
|
+
case 'channels': {
|
|
146
|
+
const target = rest[0];
|
|
147
|
+
if (target === 'status') {
|
|
148
|
+
print(await call('GET', `/v1/apps/${encodeURIComponent(needApp())}/channels/status`));
|
|
149
|
+
return 0;
|
|
150
|
+
}
|
|
151
|
+
if (!target || !UPLOAD_CHANNELS.includes(target))
|
|
152
|
+
throw new CliError(`Usage · Kullanım: pushizo channels <status|${UPLOAD_CHANNELS.join('|')}> [options]`);
|
|
153
|
+
const input = parseChannelFlags(target, rest.slice(1));
|
|
154
|
+
if (!key)
|
|
155
|
+
throw new CliError('PUSHIZO_API_KEY is required · PUSHIZO_API_KEY gerekli.');
|
|
156
|
+
// Hata gövdesi ham yazdırılmaz: durum kodu ve gövde ortak modüle verilir, o sırlardan arındırıp özetler.
|
|
157
|
+
const apiCall = async (method, path, body) => {
|
|
158
|
+
let res;
|
|
159
|
+
try {
|
|
160
|
+
res = await io.fetch(`${apiUrl}${path}`, {
|
|
161
|
+
method,
|
|
162
|
+
headers: {
|
|
163
|
+
authorization: `Bearer ${key}`,
|
|
164
|
+
accept: 'application/json',
|
|
165
|
+
'user-agent': `pushizo-cli/${VERSION}`,
|
|
166
|
+
...(body !== undefined ? { 'content-type': 'application/json' } : {}),
|
|
167
|
+
},
|
|
168
|
+
...(body !== undefined ? { body: JSON.stringify(body) } : {}),
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
catch (error) {
|
|
172
|
+
throw new CliError(`Network error · Ağ hatası: ${error instanceof Error ? error.message : String(error)}`);
|
|
173
|
+
}
|
|
174
|
+
const text = await res.text();
|
|
175
|
+
let json;
|
|
176
|
+
try {
|
|
177
|
+
json = text ? JSON.parse(text) : null;
|
|
178
|
+
}
|
|
179
|
+
catch {
|
|
180
|
+
json = null;
|
|
181
|
+
}
|
|
182
|
+
return { status: res.status, json };
|
|
183
|
+
};
|
|
184
|
+
const result = await uploadChannelCredentials(input, needApp(), { rootDir: env.PUSHIZO_CREDENTIALS_DIR?.trim() || io.cwd || process.cwd(), env }, apiCall);
|
|
185
|
+
print(result);
|
|
186
|
+
return result.ok ? 0 : 1;
|
|
187
|
+
}
|
|
97
188
|
default:
|
|
98
189
|
io.err(`Unknown command · Bilinmeyen komut: ${command}\n\n${HELP}`);
|
|
99
190
|
return 1;
|
|
100
191
|
}
|
|
101
192
|
}
|
|
102
193
|
catch (error) {
|
|
194
|
+
if (error instanceof CredentialError) {
|
|
195
|
+
io.err(`${error.code}: ${error.message}\n`);
|
|
196
|
+
return 1;
|
|
197
|
+
}
|
|
103
198
|
if (error instanceof CliError) {
|
|
104
199
|
io.err(`${error.message}\n`);
|
|
105
200
|
return 1;
|
|
@@ -0,0 +1,317 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Push anahtarını dosya YOLUNDAN yükleme (ADR-0097): yerel stdio MCP sunucusu ve `pushizo` CLI aynı kodu kullanır.
|
|
3
|
+
* Bu dosya `packages/mcp-server/src/credential-files.ts` ve `packages/cli/src/credential-files.ts` içinde aynı içerikte
|
|
4
|
+
* tutulur (yayımlanan paketler birbirine bağımlı olmaz); eşitliği birim testi zorlar.
|
|
5
|
+
*
|
|
6
|
+
* Kurallar: dosyayı yalnız bu süreç okur; içerik ve sır değerleri dönüş değerine, hata iletisine ya da günlüğe
|
|
7
|
+
* yazılmaz. Dönüş yalnız durumdur (kanal, sağlayıcı, `active`/`invalid`, hata kodu, öneri, dosya parmak izi).
|
|
8
|
+
*/
|
|
9
|
+
import { createHash } from 'node:crypto';
|
|
10
|
+
import { open, realpath } from 'node:fs/promises';
|
|
11
|
+
import path from 'node:path';
|
|
12
|
+
export const UPLOAD_CHANNELS = ['apns', 'fcm', 'hms', 'adm', 'wns', 'webpush'];
|
|
13
|
+
/** Kısa ad → public API kanal yolu. */
|
|
14
|
+
export const UPLOAD_CHANNEL_PATH = {
|
|
15
|
+
apns: 'ios_push',
|
|
16
|
+
fcm: 'android_push',
|
|
17
|
+
hms: 'hms_push',
|
|
18
|
+
adm: 'adm_push',
|
|
19
|
+
wns: 'wns_push',
|
|
20
|
+
webpush: 'web_push',
|
|
21
|
+
};
|
|
22
|
+
/** Anahtar dosyası (`.p8`, `.p12`, servis hesabı JSON'u) üst sınırı. */
|
|
23
|
+
export const MAX_KEY_FILE_BYTES = 64 * 1024;
|
|
24
|
+
/** Metin sırrı dosyası (`client_secret`, parola, VAPID özel anahtarı) üst sınırı. */
|
|
25
|
+
export const MAX_SECRET_FILE_BYTES = 4 * 1024;
|
|
26
|
+
/** PKCS#8 PEM sınırları. Parçalı yazılır: gizli bilgi tarayıcıları tam başlığı anahtar sanmasın. */
|
|
27
|
+
const PEM_DASHES = '-----';
|
|
28
|
+
const PEM_HEAD = `${PEM_DASHES}BEGIN PRIVATE KEY${PEM_DASHES}`;
|
|
29
|
+
const PEM_TAIL = `${PEM_DASHES}END PRIVATE KEY${PEM_DASHES}`;
|
|
30
|
+
const ENV_NAME = /^[A-Z][A-Z0-9_]*$/;
|
|
31
|
+
/** Sır kaynağı olarak okunamayan ortam değişkenleri (Pushizo API anahtarı başka yere taşınmaz). */
|
|
32
|
+
const FORBIDDEN_ENV = new Set(['PUSHIZO_API_KEY']);
|
|
33
|
+
/** Yerel denetim hatası (yol, boyut, biçim, eksik alan). İleti hiçbir dosya içeriği taşımaz. */
|
|
34
|
+
export class CredentialError extends Error {
|
|
35
|
+
code;
|
|
36
|
+
constructor(code, message) {
|
|
37
|
+
super(message);
|
|
38
|
+
this.code = code;
|
|
39
|
+
this.name = 'CredentialError';
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
function isInside(root, target) {
|
|
43
|
+
const rel = path.relative(root, target);
|
|
44
|
+
return rel !== '' && !rel.startsWith('..') && !path.isAbsolute(rel);
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Kullanıcının verdiği yolu kök dizin altında gerçek yola çözer. Kök dışına çıkan yol (`..`, mutlak yol, sembolik
|
|
48
|
+
* bağ) reddedilir; dosya sistemi kökü kök dizin olarak kabul edilmez.
|
|
49
|
+
*/
|
|
50
|
+
export async function resolveInside(rootDir, userPath) {
|
|
51
|
+
if (typeof userPath !== 'string' || userPath.trim() === '' || userPath.includes('\0'))
|
|
52
|
+
throw new CredentialError('PATH_INVALID', 'A file path is required.');
|
|
53
|
+
let root;
|
|
54
|
+
try {
|
|
55
|
+
root = await realpath(rootDir);
|
|
56
|
+
}
|
|
57
|
+
catch {
|
|
58
|
+
throw new CredentialError('ROOT_NOT_FOUND', 'The credentials directory does not exist.');
|
|
59
|
+
}
|
|
60
|
+
if (root === path.parse(root).root)
|
|
61
|
+
throw new CredentialError('ROOT_NOT_ALLOWED', 'The filesystem root cannot be the credentials directory. Start the process in your project folder or set PUSHIZO_CREDENTIALS_DIR.');
|
|
62
|
+
const candidate = path.resolve(root, userPath.trim());
|
|
63
|
+
if (!isInside(root, candidate))
|
|
64
|
+
throw new CredentialError('PATH_OUTSIDE_ROOT', 'The file must be inside the credentials directory (the working directory or PUSHIZO_CREDENTIALS_DIR).');
|
|
65
|
+
let real;
|
|
66
|
+
try {
|
|
67
|
+
real = await realpath(candidate);
|
|
68
|
+
}
|
|
69
|
+
catch {
|
|
70
|
+
throw new CredentialError('FILE_NOT_FOUND', `File not found: ${path.basename(candidate)}`);
|
|
71
|
+
}
|
|
72
|
+
if (!isInside(root, real))
|
|
73
|
+
throw new CredentialError('PATH_OUTSIDE_ROOT', 'The file resolves outside the credentials directory (symbolic link).');
|
|
74
|
+
return real;
|
|
75
|
+
}
|
|
76
|
+
/** Kök altındaki normal dosyayı boyut sınırıyla okur. */
|
|
77
|
+
export async function readBoundedFile(rootDir, userPath, maxBytes) {
|
|
78
|
+
const real = await resolveInside(rootDir, userPath);
|
|
79
|
+
const handle = await open(real, 'r');
|
|
80
|
+
try {
|
|
81
|
+
const info = await handle.stat();
|
|
82
|
+
if (!info.isFile())
|
|
83
|
+
throw new CredentialError('NOT_A_FILE', `Not a regular file: ${path.basename(real)}`);
|
|
84
|
+
if (info.size === 0)
|
|
85
|
+
throw new CredentialError('FILE_EMPTY', `File is empty: ${path.basename(real)}`);
|
|
86
|
+
if (info.size > maxBytes)
|
|
87
|
+
throw new CredentialError('FILE_TOO_LARGE', `File is larger than ${maxBytes} bytes: ${path.basename(real)}`);
|
|
88
|
+
const data = await handle.readFile();
|
|
89
|
+
if (data.length > maxBytes)
|
|
90
|
+
throw new CredentialError('FILE_TOO_LARGE', `File is larger than ${maxBytes} bytes: ${path.basename(real)}`);
|
|
91
|
+
return { real, data };
|
|
92
|
+
}
|
|
93
|
+
finally {
|
|
94
|
+
await handle.close();
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
function fingerprint(real, data) {
|
|
98
|
+
return { name: path.basename(real), bytes: data.length, sha256: createHash('sha256').update(data).digest('hex').slice(0, 12) };
|
|
99
|
+
}
|
|
100
|
+
/** `AuthKey_ABCDE12345.p8` → `ABCDE12345` (Apple'ın indirdiği dosya adı); eşleşmezse null. */
|
|
101
|
+
export function keyIdFromP8FileName(name) {
|
|
102
|
+
const m = /^AuthKey_([A-Za-z0-9]{10})(?:\s*\(\d+\))?\.p8$/i.exec(path.basename(name).trim());
|
|
103
|
+
return m ? m[1].toUpperCase() : null;
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* Metin sırrı: yalnız dosya yolu ya da ortam değişkeni ADI ile verilir; değerin kendisi argüman olamaz.
|
|
107
|
+
* İkisi de verilmediyse `undefined` (güncellemede kayıtlı sır korunur).
|
|
108
|
+
*/
|
|
109
|
+
export async function readTextSecret(host, source, label) {
|
|
110
|
+
if (source.file && source.env)
|
|
111
|
+
throw new CredentialError('SECRET_SOURCE_CONFLICT', `Give either ${label}_file or ${label}_env, not both.`);
|
|
112
|
+
if (source.file) {
|
|
113
|
+
const { data } = await readBoundedFile(host.rootDir, source.file, MAX_SECRET_FILE_BYTES);
|
|
114
|
+
const value = data.toString('utf8').trim();
|
|
115
|
+
if (!value || /[\r\n]/.test(value))
|
|
116
|
+
throw new CredentialError('SECRET_FILE_INVALID', `${label}_file must contain a single non-empty line.`);
|
|
117
|
+
return value;
|
|
118
|
+
}
|
|
119
|
+
if (source.env) {
|
|
120
|
+
if (!ENV_NAME.test(source.env) || FORBIDDEN_ENV.has(source.env))
|
|
121
|
+
throw new CredentialError('ENV_NAME_INVALID', `${label}_env must be an environment variable NAME (A-Z, 0-9, _), not a value.`);
|
|
122
|
+
const value = host.env[source.env]?.trim();
|
|
123
|
+
if (!value)
|
|
124
|
+
throw new CredentialError('ENV_NOT_SET', `Environment variable ${source.env} is not set in the process that runs this tool.`);
|
|
125
|
+
return value;
|
|
126
|
+
}
|
|
127
|
+
return undefined;
|
|
128
|
+
}
|
|
129
|
+
function required(input, fields) {
|
|
130
|
+
const missing = fields.filter((f) => input[f] === undefined || input[f] === '');
|
|
131
|
+
if (missing.length)
|
|
132
|
+
throw new CredentialError('MISSING_FIELD', `Missing: ${missing.join(', ')}.`);
|
|
133
|
+
}
|
|
134
|
+
function extensionOf(file) {
|
|
135
|
+
return path.extname(file).toLowerCase();
|
|
136
|
+
}
|
|
137
|
+
/** PEM gövdesinin satırları da sır sayılır (ileti içinde parça olarak geçebilir). */
|
|
138
|
+
function pemSecrets(pem) {
|
|
139
|
+
return [pem, ...pem.split(/\r?\n/).map((l) => l.trim()).filter((l) => l.length >= 16 && !l.startsWith(PEM_DASHES))];
|
|
140
|
+
}
|
|
141
|
+
/** Girdi ve dosyalardan `PUT /v1/apps/{app}/channels/{channel}` gövdesini üretir; biçimi yerelde doğrular. */
|
|
142
|
+
export async function buildChannelCredentials(input, host) {
|
|
143
|
+
switch (input.channel) {
|
|
144
|
+
case 'apns': {
|
|
145
|
+
required(input, ['key_file']);
|
|
146
|
+
const ext = extensionOf(input.key_file);
|
|
147
|
+
if (ext === '.p8') {
|
|
148
|
+
const { real, data } = await readBoundedFile(host.rootDir, input.key_file, MAX_KEY_FILE_BYTES);
|
|
149
|
+
const pem = data.toString('utf8').trim();
|
|
150
|
+
if (!pem.startsWith(PEM_HEAD) || !pem.endsWith(PEM_TAIL) || pem.length <= PEM_HEAD.length + PEM_TAIL.length)
|
|
151
|
+
throw new CredentialError('KEY_FORMAT_INVALID', 'The .p8 file is not a PKCS#8 PEM private key (expected a "BEGIN PRIVATE KEY" header).');
|
|
152
|
+
const keyId = (input.key_id ?? keyIdFromP8FileName(real) ?? '').toUpperCase();
|
|
153
|
+
if (!keyId)
|
|
154
|
+
throw new CredentialError('MISSING_FIELD', 'Missing: key_id (not found in the file name; expected AuthKey_XXXXXXXXXX.p8).');
|
|
155
|
+
required(input, ['team_id', 'bundle_id', 'environment']);
|
|
156
|
+
return {
|
|
157
|
+
provider: 'apns',
|
|
158
|
+
body: { provider: 'apns', key_id: keyId, team_id: input.team_id, bundle_id: input.bundle_id, environment: input.environment, p8: pem },
|
|
159
|
+
file: fingerprint(real, data),
|
|
160
|
+
secrets: pemSecrets(pem),
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
if (ext === '.p12') {
|
|
164
|
+
const { real, data } = await readBoundedFile(host.rootDir, input.key_file, MAX_KEY_FILE_BYTES);
|
|
165
|
+
if (data[0] !== 0x30)
|
|
166
|
+
throw new CredentialError('KEY_FORMAT_INVALID', 'The .p12 file is not a PKCS#12 (DER) container.');
|
|
167
|
+
const password = await readTextSecret(host, { file: input.p12_password_file, env: input.p12_password_env }, 'p12_password');
|
|
168
|
+
const p12 = data.toString('base64');
|
|
169
|
+
return {
|
|
170
|
+
provider: 'apns',
|
|
171
|
+
body: { provider: 'apns', p12, ...(password !== undefined ? { p12_password: password } : {}), ...(input.bundle_id ? { bundle_id: input.bundle_id } : {}) },
|
|
172
|
+
file: fingerprint(real, data),
|
|
173
|
+
secrets: [p12, ...(password ? [password] : [])],
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
throw new CredentialError('KEY_EXTENSION_INVALID', 'APNs needs a .p8 (token) or .p12 (certificate) file.');
|
|
177
|
+
}
|
|
178
|
+
case 'fcm': {
|
|
179
|
+
required(input, ['key_file']);
|
|
180
|
+
if (extensionOf(input.key_file) !== '.json')
|
|
181
|
+
throw new CredentialError('KEY_EXTENSION_INVALID', 'FCM needs the Firebase service account .json file.');
|
|
182
|
+
const { real, data } = await readBoundedFile(host.rootDir, input.key_file, MAX_KEY_FILE_BYTES);
|
|
183
|
+
let parsed;
|
|
184
|
+
try {
|
|
185
|
+
parsed = JSON.parse(data.toString('utf8'));
|
|
186
|
+
}
|
|
187
|
+
catch {
|
|
188
|
+
throw new CredentialError('KEY_FORMAT_INVALID', 'The file is not valid JSON.');
|
|
189
|
+
}
|
|
190
|
+
const sa = (typeof parsed === 'object' && parsed !== null ? parsed : {});
|
|
191
|
+
if (sa.type !== 'service_account' || typeof sa.project_id !== 'string' || typeof sa.client_email !== 'string' || typeof sa.private_key !== 'string' || !sa.private_key.includes(`PRIVATE KEY${PEM_DASHES}`))
|
|
192
|
+
throw new CredentialError('KEY_FORMAT_INVALID', 'The JSON is not a Firebase service account key (needs type: service_account, project_id, client_email, private_key). google-services.json is a different file.');
|
|
193
|
+
return {
|
|
194
|
+
provider: 'fcm',
|
|
195
|
+
body: {
|
|
196
|
+
provider: 'fcm',
|
|
197
|
+
service_account: {
|
|
198
|
+
type: 'service_account',
|
|
199
|
+
project_id: sa.project_id,
|
|
200
|
+
client_email: sa.client_email,
|
|
201
|
+
private_key: sa.private_key,
|
|
202
|
+
...(typeof sa.token_uri === 'string' ? { token_uri: sa.token_uri } : {}),
|
|
203
|
+
},
|
|
204
|
+
...(input.confirm_project_change ? { confirm_project_change: true } : {}),
|
|
205
|
+
},
|
|
206
|
+
file: fingerprint(real, data),
|
|
207
|
+
secrets: pemSecrets(sa.private_key),
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
case 'hms':
|
|
211
|
+
case 'adm':
|
|
212
|
+
case 'wns': {
|
|
213
|
+
const idField = input.channel === 'hms' ? 'hms_app_id' : input.channel === 'adm' ? 'client_id' : 'package_sid';
|
|
214
|
+
required(input, [idField]);
|
|
215
|
+
const secret = await readTextSecret(host, { file: input.client_secret_file, env: input.client_secret_env }, 'client_secret');
|
|
216
|
+
const idKey = input.channel === 'hms' ? 'app_id' : idField;
|
|
217
|
+
return {
|
|
218
|
+
provider: input.channel,
|
|
219
|
+
body: {
|
|
220
|
+
provider: input.channel,
|
|
221
|
+
[idKey]: input[idField],
|
|
222
|
+
...(secret !== undefined ? { client_secret: secret } : {}),
|
|
223
|
+
...(input.channel === 'hms' && input.high_priority !== undefined ? { high_priority: input.high_priority } : {}),
|
|
224
|
+
},
|
|
225
|
+
file: null,
|
|
226
|
+
secrets: secret ? [secret] : [],
|
|
227
|
+
};
|
|
228
|
+
}
|
|
229
|
+
case 'webpush': {
|
|
230
|
+
required(input, ['subject']);
|
|
231
|
+
const privateKey = await readTextSecret(host, { file: input.vapid_private_key_file, env: input.vapid_private_key_env }, 'vapid_private_key');
|
|
232
|
+
if ((privateKey === undefined) !== (input.vapid_public_key === undefined))
|
|
233
|
+
throw new CredentialError('MISSING_FIELD', 'Give vapid_public_key together with vapid_private_key_file/_env, or neither (a new key pair is generated).');
|
|
234
|
+
return {
|
|
235
|
+
provider: 'webpush',
|
|
236
|
+
body: {
|
|
237
|
+
provider: 'webpush',
|
|
238
|
+
subject: input.subject,
|
|
239
|
+
...(input.site_url ? { site_url: input.site_url } : {}),
|
|
240
|
+
...(privateKey !== undefined ? { vapid_public_key: input.vapid_public_key, vapid_private_key: privateKey } : {}),
|
|
241
|
+
},
|
|
242
|
+
file: null,
|
|
243
|
+
secrets: privateKey ? [privateKey] : [],
|
|
244
|
+
};
|
|
245
|
+
}
|
|
246
|
+
default:
|
|
247
|
+
throw new CredentialError('CHANNEL_INVALID', `Unknown channel. Use one of: ${UPLOAD_CHANNELS.join(', ')}.`);
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
/** İletiyi okunan sır değerlerinden arındırır ve kısaltır. */
|
|
251
|
+
export function scrubSecrets(text, secrets) {
|
|
252
|
+
let out = text;
|
|
253
|
+
for (const secret of [...secrets].sort((a, b) => b.length - a.length))
|
|
254
|
+
if (secret.length >= 4)
|
|
255
|
+
out = out.split(secret).join('[redacted]');
|
|
256
|
+
return out.length > 300 ? `${out.slice(0, 300)}…` : out;
|
|
257
|
+
}
|
|
258
|
+
const HINTS = {
|
|
259
|
+
auth: 'The provider rejected the credentials. Check that the key belongs to this app (APNs: Key ID, Team ID, bundle id, environment; FCM: the service account of the same Firebase project) and has not been revoked.',
|
|
260
|
+
config: 'The configuration is incomplete or inconsistent. Check the identifiers passed with the file.',
|
|
261
|
+
transient: 'The provider could not be reached. The credentials are saved; run the upload or validation again in a moment.',
|
|
262
|
+
HTTP_401: 'The Pushizo API key is invalid, expired or revoked.',
|
|
263
|
+
HTTP_403: 'Uploading channel credentials needs an API key with the `admin` scope that can access this app.',
|
|
264
|
+
HTTP_404: 'The app was not found for this API key. Check app_id.',
|
|
265
|
+
HTTP_429: 'Rate limited. Wait a minute and try again.',
|
|
266
|
+
HS_VALIDATION_ERROR: 'The API rejected a field. Check the identifiers (Key ID and Team ID are 10 characters; bundle id; numeric HMS App ID).',
|
|
267
|
+
HS_PLAN_FEATURE_REQUIRED: 'This channel is not included in the organization plan.',
|
|
268
|
+
};
|
|
269
|
+
function errorOf(json) {
|
|
270
|
+
const err = json?.error;
|
|
271
|
+
return { code: typeof err?.code === 'string' ? err.code : null, message: typeof err?.message === 'string' ? err.message : null };
|
|
272
|
+
}
|
|
273
|
+
/**
|
|
274
|
+
* Anahtarı dosyadan okur, kaydeder ve sağlayıcıya doğrulatır. Dönüş yalnız durumdur; API'nin döndürdüğü yapılandırma
|
|
275
|
+
* ayrıntısı ve okunan içerik dönüşe girmez.
|
|
276
|
+
*/
|
|
277
|
+
export async function uploadChannelCredentials(input, appId, host, call) {
|
|
278
|
+
const built = await buildChannelCredentials(input, host);
|
|
279
|
+
const channel = UPLOAD_CHANNEL_PATH[input.channel];
|
|
280
|
+
const base = `/v1/apps/${encodeURIComponent(appId)}/channels/${channel}`;
|
|
281
|
+
const result = (patch) => ({
|
|
282
|
+
channel,
|
|
283
|
+
provider: built.provider,
|
|
284
|
+
saved: false,
|
|
285
|
+
ok: false,
|
|
286
|
+
status: 'not_saved',
|
|
287
|
+
error_code: null,
|
|
288
|
+
message: null,
|
|
289
|
+
hint: null,
|
|
290
|
+
file: built.file,
|
|
291
|
+
...patch,
|
|
292
|
+
});
|
|
293
|
+
const saved = await call('PUT', base, built.body);
|
|
294
|
+
if (saved.status < 200 || saved.status >= 300) {
|
|
295
|
+
const err = errorOf(saved.json);
|
|
296
|
+
const code = err.code ?? `HTTP_${saved.status}`;
|
|
297
|
+
return result({ error_code: code, message: err.message ? scrubSecrets(err.message, built.secrets) : null, hint: HINTS[code] ?? HINTS[`HTTP_${saved.status}`] ?? null });
|
|
298
|
+
}
|
|
299
|
+
const checked = await call('POST', `${base}/validate`);
|
|
300
|
+
if (checked.status < 200 || checked.status >= 300) {
|
|
301
|
+
const err = errorOf(checked.json);
|
|
302
|
+
const code = err.code ?? `HTTP_${checked.status}`;
|
|
303
|
+
return result({ saved: true, status: 'unverified', error_code: code, message: err.message ? scrubSecrets(err.message, built.secrets) : null, hint: HINTS[code] ?? HINTS[`HTTP_${checked.status}`] ?? HINTS.transient });
|
|
304
|
+
}
|
|
305
|
+
const view = (checked.json ?? {});
|
|
306
|
+
const ok = view.ok === true;
|
|
307
|
+
const status = typeof view.channel?.status === 'string' ? view.channel.status : ok ? 'active' : 'invalid';
|
|
308
|
+
if (ok)
|
|
309
|
+
return result({ saved: true, ok: true, status });
|
|
310
|
+
return result({
|
|
311
|
+
saved: true,
|
|
312
|
+
status,
|
|
313
|
+
error_code: typeof view.code === 'string' ? view.code : 'VALIDATION_FAILED',
|
|
314
|
+
message: typeof view.message === 'string' ? scrubSecrets(view.message, built.secrets) : null,
|
|
315
|
+
hint: (typeof view.kind === 'string' ? HINTS[view.kind] : undefined) ?? HINTS.config,
|
|
316
|
+
});
|
|
317
|
+
}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@pushizo/cli",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "Pushizo command-line tool: list apps, segments and templates, send notifications",
|
|
3
|
+
"version": "0.4.0",
|
|
4
|
+
"description": "Pushizo command-line tool: list apps, segments and templates, send notifications, upload push credentials from a file",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"homepage": "https://docs.pushizo.com/docs/integrations/cli-sdks",
|
|
7
7
|
"repository": {
|
|
@@ -25,7 +25,7 @@
|
|
|
25
25
|
},
|
|
26
26
|
"type": "module",
|
|
27
27
|
"bin": {
|
|
28
|
-
"pushizo": "
|
|
28
|
+
"pushizo": "dist/index.js"
|
|
29
29
|
},
|
|
30
30
|
"files": [
|
|
31
31
|
"dist",
|