未コミットを一括コミット
This commit is contained in:
@@ -1,6 +1,6 @@
|
||||
# alexa-api/.env
|
||||
# このファイルをコピーして .env を作成し、ALEXA_COOKIE に値を設定する
|
||||
# .env は Git にコミットしない(.gitignore 参照)
|
||||
|
||||
# Amazon Cookie(auth.js を実行して取得)
|
||||
ALEXA_COOKIE=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
|
||||
# alexa-api/.env
|
||||
# このファイルをコピーして .env を作成し、ALEXA_COOKIE に値を設定する
|
||||
# .env は Git にコミットしない(.gitignore 参照)
|
||||
|
||||
# Amazon Cookie(auth.js を実行して取得)
|
||||
ALEXA_COOKIE=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
|
||||
|
||||
4
alexa-api/.gitignore
vendored
4
alexa-api/.gitignore
vendored
@@ -1,2 +1,2 @@
|
||||
node_modules/
|
||||
.env
|
||||
node_modules/
|
||||
.env
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
FROM node:20-alpine
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# 依存パッケージのみ先にコピー(キャッシュ活用)
|
||||
COPY package*.json ./
|
||||
RUN npm install --omit=dev
|
||||
|
||||
# ソースをコピー
|
||||
COPY server.js .
|
||||
|
||||
EXPOSE 3500
|
||||
|
||||
CMD ["node", "server.js"]
|
||||
FROM node:20-alpine
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# 依存パッケージのみ先にコピー(キャッシュ活用)
|
||||
COPY package*.json ./
|
||||
RUN npm install --omit=dev
|
||||
|
||||
# ソースをコピー
|
||||
COPY server.js .
|
||||
|
||||
EXPOSE 3500
|
||||
|
||||
CMD ["node", "server.js"]
|
||||
|
||||
@@ -1,70 +1,70 @@
|
||||
/**
|
||||
* alexa-api/auth.js
|
||||
* ローカル PC で実行して Amazon Cookie を取得するスクリプト。
|
||||
*
|
||||
* 使い方:
|
||||
* cd alexa-api
|
||||
* npm install alexa-cookie2
|
||||
* node auth.js
|
||||
*
|
||||
* → ブラウザで http://localhost:3456 を開く
|
||||
* → Amazon にログイン
|
||||
* → コンソールに Cookie が表示される
|
||||
* → その値を Windmill Variable "u/admin/ALEXA_COOKIE" に登録
|
||||
*/
|
||||
|
||||
const AlexaCookie = require('alexa-cookie2');
|
||||
|
||||
const PROXY_PORT = 3456;
|
||||
|
||||
console.log('==============================================');
|
||||
console.log(' Alexa Cookie 取得ツール');
|
||||
console.log('==============================================');
|
||||
console.log(`\n認証プロキシを起動中... (port ${PROXY_PORT})`);
|
||||
console.log('\n【手順】');
|
||||
console.log(` 1. ブラウザで http://localhost:${PROXY_PORT} を開く`);
|
||||
console.log(' 2. Amazon アカウントにログイン(amazon.co.jp)');
|
||||
console.log(' 3. ログイン完了後、このコンソールに Cookie が表示される\n');
|
||||
|
||||
AlexaCookie.generateAlexaCookie(
|
||||
'',
|
||||
{
|
||||
amazonPage: 'amazon.co.jp',
|
||||
acceptLanguage: 'ja-JP',
|
||||
setupProxy: true,
|
||||
proxyPort: PROXY_PORT,
|
||||
proxyOwnIp: '127.0.0.1',
|
||||
proxyListenBind: '0.0.0.0',
|
||||
logger: (msg) => {
|
||||
if (!msg.includes('verbose') && !msg.includes('DEBUG')) {
|
||||
console.log('[auth]', msg);
|
||||
}
|
||||
},
|
||||
},
|
||||
(err, cookie) => {
|
||||
// alexa-cookie2 はブラウザを開くよう促すメッセージも err として渡してくる
|
||||
if (err) {
|
||||
const msg = err.message || String(err);
|
||||
if (msg.includes('Please open')) {
|
||||
// これは実際のエラーではなく「ブラウザで開いて」という指示
|
||||
console.log('\n>>> ブラウザで http://localhost:3456/ を開いて Amazon にログインしてください <<<\n');
|
||||
// プロキシを生かしたまま待機(process.exit しない)
|
||||
return;
|
||||
}
|
||||
console.error('\n[ERROR] 認証失敗:', msg);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
console.log('\n==============================================');
|
||||
console.log(' Cookie 取得成功!');
|
||||
console.log('==============================================');
|
||||
console.log('\n以下の値を Windmill Variable に登録してください:');
|
||||
console.log(' パス: u/admin/ALEXA_COOKIE');
|
||||
console.log(' Secret: ON(チェックを入れる)');
|
||||
console.log('\n--- Cookie ---');
|
||||
console.log(cookie);
|
||||
console.log('--- ここまで ---\n');
|
||||
|
||||
process.exit(0);
|
||||
}
|
||||
);
|
||||
/**
|
||||
* alexa-api/auth.js
|
||||
* ローカル PC で実行して Amazon Cookie を取得するスクリプト。
|
||||
*
|
||||
* 使い方:
|
||||
* cd alexa-api
|
||||
* npm install alexa-cookie2
|
||||
* node auth.js
|
||||
*
|
||||
* → ブラウザで http://localhost:3456 を開く
|
||||
* → Amazon にログイン
|
||||
* → コンソールに Cookie が表示される
|
||||
* → その値を Windmill Variable "u/admin/ALEXA_COOKIE" に登録
|
||||
*/
|
||||
|
||||
const AlexaCookie = require('alexa-cookie2');
|
||||
|
||||
const PROXY_PORT = 3456;
|
||||
|
||||
console.log('==============================================');
|
||||
console.log(' Alexa Cookie 取得ツール');
|
||||
console.log('==============================================');
|
||||
console.log(`\n認証プロキシを起動中... (port ${PROXY_PORT})`);
|
||||
console.log('\n【手順】');
|
||||
console.log(` 1. ブラウザで http://localhost:${PROXY_PORT} を開く`);
|
||||
console.log(' 2. Amazon アカウントにログイン(amazon.co.jp)');
|
||||
console.log(' 3. ログイン完了後、このコンソールに Cookie が表示される\n');
|
||||
|
||||
AlexaCookie.generateAlexaCookie(
|
||||
'',
|
||||
{
|
||||
amazonPage: 'amazon.co.jp',
|
||||
acceptLanguage: 'ja-JP',
|
||||
setupProxy: true,
|
||||
proxyPort: PROXY_PORT,
|
||||
proxyOwnIp: '127.0.0.1',
|
||||
proxyListenBind: '0.0.0.0',
|
||||
logger: (msg) => {
|
||||
if (!msg.includes('verbose') && !msg.includes('DEBUG')) {
|
||||
console.log('[auth]', msg);
|
||||
}
|
||||
},
|
||||
},
|
||||
(err, cookie) => {
|
||||
// alexa-cookie2 はブラウザを開くよう促すメッセージも err として渡してくる
|
||||
if (err) {
|
||||
const msg = err.message || String(err);
|
||||
if (msg.includes('Please open')) {
|
||||
// これは実際のエラーではなく「ブラウザで開いて」という指示
|
||||
console.log('\n>>> ブラウザで http://localhost:3456/ を開いて Amazon にログインしてください <<<\n');
|
||||
// プロキシを生かしたまま待機(process.exit しない)
|
||||
return;
|
||||
}
|
||||
console.error('\n[ERROR] 認証失敗:', msg);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
console.log('\n==============================================');
|
||||
console.log(' Cookie 取得成功!');
|
||||
console.log('==============================================');
|
||||
console.log('\n以下の値を Windmill Variable に登録してください:');
|
||||
console.log(' パス: u/admin/ALEXA_COOKIE');
|
||||
console.log(' Secret: ON(チェックを入れる)');
|
||||
console.log('\n--- Cookie ---');
|
||||
console.log(cookie);
|
||||
console.log('--- ここまで ---\n');
|
||||
|
||||
process.exit(0);
|
||||
}
|
||||
);
|
||||
|
||||
@@ -1,76 +1,76 @@
|
||||
/**
|
||||
* auth2.js - alexa-remote2 自身の認証フローを使う
|
||||
* alexa-cookie2 より確実(ライブラリ内蔵の OAuth プロキシを使用)
|
||||
*
|
||||
* 使い方:
|
||||
* node auth2.js
|
||||
* → ブラウザで http://localhost:3001/ を開いて Amazon にログイン
|
||||
* → 成功するとコンソールに Cookie が出力される → .env に保存
|
||||
*/
|
||||
|
||||
const AlexaRemote = require('alexa-remote2');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
const PORT = 3001;
|
||||
|
||||
console.log('==============================================');
|
||||
console.log(' Alexa 認証ツール (alexa-remote2 内蔵プロキシ)');
|
||||
console.log('==============================================');
|
||||
console.log(`\nプロキシ起動中... (port ${PORT})`);
|
||||
console.log(`\n【手順】ブラウザで http://localhost:${PORT}/ を開いて Amazon にログイン\n`);
|
||||
|
||||
const alexa = new AlexaRemote();
|
||||
|
||||
alexa.init(
|
||||
{
|
||||
cookie: null,
|
||||
alexaServiceHost: 'alexa.amazon.co.jp',
|
||||
amazonPage: 'amazon.co.jp',
|
||||
acceptLanguage: 'ja-JP',
|
||||
useWsMqtt: false,
|
||||
setupProxy: true,
|
||||
proxyOwnIp: '127.0.0.1',
|
||||
proxyPort: PORT,
|
||||
proxyListenBind: '0.0.0.0',
|
||||
logger: console.log,
|
||||
onSucess: (refreshedCookie) => {
|
||||
// 認証成功時にリフレッシュされた Cookie を受け取る
|
||||
console.log('\n[onSucess] Cookie refreshed');
|
||||
},
|
||||
},
|
||||
(err, result) => {
|
||||
if (err) {
|
||||
const msg = err.message || String(err);
|
||||
if (msg.includes('open') && (msg.includes('http://') || msg.includes('localhost'))) {
|
||||
console.log(`\n>>> ブラウザで http://localhost:${PORT}/ を開いてください <<<\n`);
|
||||
// プロキシを生かしたまま待機
|
||||
return;
|
||||
}
|
||||
console.error('\n[ERROR]', msg);
|
||||
return;
|
||||
}
|
||||
|
||||
// 認証成功
|
||||
console.log('\n==============================================');
|
||||
console.log(' 認証成功!');
|
||||
console.log('==============================================');
|
||||
|
||||
// alexa-remote2 内部の Cookie を取得
|
||||
const cookie = alexa.cookie || alexa._options?.cookie;
|
||||
if (cookie) {
|
||||
const cookieStr = typeof cookie === 'string' ? cookie : JSON.stringify(cookie);
|
||||
console.log('\n以下を alexa-api/.env の ALEXA_COOKIE に設定してください:\n');
|
||||
console.log('ALEXA_COOKIE=' + cookieStr);
|
||||
|
||||
// .env に自動保存
|
||||
const envPath = path.join(__dirname, '.env');
|
||||
fs.writeFileSync(envPath, 'ALEXA_COOKIE=' + cookieStr + '\n');
|
||||
console.log(`\n.env に自動保存しました: ${envPath}`);
|
||||
} else {
|
||||
console.log('Cookie を取得できませんでした。alexa オブジェクト:', Object.keys(alexa));
|
||||
}
|
||||
|
||||
process.exit(0);
|
||||
}
|
||||
);
|
||||
/**
|
||||
* auth2.js - alexa-remote2 自身の認証フローを使う
|
||||
* alexa-cookie2 より確実(ライブラリ内蔵の OAuth プロキシを使用)
|
||||
*
|
||||
* 使い方:
|
||||
* node auth2.js
|
||||
* → ブラウザで http://localhost:3001/ を開いて Amazon にログイン
|
||||
* → 成功するとコンソールに Cookie が出力される → .env に保存
|
||||
*/
|
||||
|
||||
const AlexaRemote = require('alexa-remote2');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
const PORT = 3001;
|
||||
|
||||
console.log('==============================================');
|
||||
console.log(' Alexa 認証ツール (alexa-remote2 内蔵プロキシ)');
|
||||
console.log('==============================================');
|
||||
console.log(`\nプロキシ起動中... (port ${PORT})`);
|
||||
console.log(`\n【手順】ブラウザで http://localhost:${PORT}/ を開いて Amazon にログイン\n`);
|
||||
|
||||
const alexa = new AlexaRemote();
|
||||
|
||||
alexa.init(
|
||||
{
|
||||
cookie: null,
|
||||
alexaServiceHost: 'alexa.amazon.co.jp',
|
||||
amazonPage: 'amazon.co.jp',
|
||||
acceptLanguage: 'ja-JP',
|
||||
useWsMqtt: false,
|
||||
setupProxy: true,
|
||||
proxyOwnIp: '127.0.0.1',
|
||||
proxyPort: PORT,
|
||||
proxyListenBind: '0.0.0.0',
|
||||
logger: console.log,
|
||||
onSucess: (refreshedCookie) => {
|
||||
// 認証成功時にリフレッシュされた Cookie を受け取る
|
||||
console.log('\n[onSucess] Cookie refreshed');
|
||||
},
|
||||
},
|
||||
(err, result) => {
|
||||
if (err) {
|
||||
const msg = err.message || String(err);
|
||||
if (msg.includes('open') && (msg.includes('http://') || msg.includes('localhost'))) {
|
||||
console.log(`\n>>> ブラウザで http://localhost:${PORT}/ を開いてください <<<\n`);
|
||||
// プロキシを生かしたまま待機
|
||||
return;
|
||||
}
|
||||
console.error('\n[ERROR]', msg);
|
||||
return;
|
||||
}
|
||||
|
||||
// 認証成功
|
||||
console.log('\n==============================================');
|
||||
console.log(' 認証成功!');
|
||||
console.log('==============================================');
|
||||
|
||||
// alexa-remote2 内部の Cookie を取得
|
||||
const cookie = alexa.cookie || alexa._options?.cookie;
|
||||
if (cookie) {
|
||||
const cookieStr = typeof cookie === 'string' ? cookie : JSON.stringify(cookie);
|
||||
console.log('\n以下を alexa-api/.env の ALEXA_COOKIE に設定してください:\n');
|
||||
console.log('ALEXA_COOKIE=' + cookieStr);
|
||||
|
||||
// .env に自動保存
|
||||
const envPath = path.join(__dirname, '.env');
|
||||
fs.writeFileSync(envPath, 'ALEXA_COOKIE=' + cookieStr + '\n');
|
||||
console.log(`\n.env に自動保存しました: ${envPath}`);
|
||||
} else {
|
||||
console.log('Cookie を取得できませんでした。alexa オブジェクト:', Object.keys(alexa));
|
||||
}
|
||||
|
||||
process.exit(0);
|
||||
}
|
||||
);
|
||||
|
||||
@@ -1,76 +1,76 @@
|
||||
/**
|
||||
* auth3.js - メール/パスワードで直接認証(2FA なしのアカウント向け)
|
||||
*
|
||||
* 使い方:
|
||||
* AMAZON_EMAIL="xxx@xxx.com" AMAZON_PASSWORD="yourpass" node auth3.js
|
||||
*
|
||||
* 成功すると .env を更新して終了します。
|
||||
*/
|
||||
|
||||
const AlexaRemote = require('alexa-remote2');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
const email = process.env.AMAZON_EMAIL;
|
||||
const password = process.env.AMAZON_PASSWORD;
|
||||
|
||||
if (!email || !password) {
|
||||
console.error('[ERROR] 環境変数 AMAZON_EMAIL と AMAZON_PASSWORD を設定してください');
|
||||
console.error(' 例: AMAZON_EMAIL="xxx@xxx.com" AMAZON_PASSWORD="pass" node auth3.js');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
console.log(`[INFO] ${email} でログイン試行中...`);
|
||||
|
||||
const alexa = new AlexaRemote();
|
||||
|
||||
alexa.init(
|
||||
{
|
||||
email,
|
||||
password,
|
||||
alexaServiceHost: 'alexa.amazon.co.jp',
|
||||
amazonPage: 'amazon.co.jp',
|
||||
acceptLanguage: 'ja-JP',
|
||||
useWsMqtt: false,
|
||||
setupProxy: false,
|
||||
logger: (msg) => {
|
||||
if (!msg.includes('verbose') && !msg.includes('Bearer')) {
|
||||
console.log('[alexa]', msg);
|
||||
}
|
||||
},
|
||||
onSucess: (refreshedCookie) => {
|
||||
saveCookie(refreshedCookie, 'onSucess refresh');
|
||||
},
|
||||
},
|
||||
(err) => {
|
||||
if (err) {
|
||||
console.error('[ERROR] 認証失敗(詳細):', err);
|
||||
console.error('\n考えられる原因:');
|
||||
console.error(' - パスワードが違う');
|
||||
console.error(' - Amazon が CAPTCHA を要求している(後で再試行)');
|
||||
console.error(' - 2FA が実際は有効になっている');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// 認証成功
|
||||
const cookie = alexa.cookie;
|
||||
saveCookie(cookie, 'init success');
|
||||
process.exit(0);
|
||||
}
|
||||
);
|
||||
|
||||
function saveCookie(cookie, source) {
|
||||
if (!cookie) {
|
||||
console.error(`[${source}] Cookie が空です`);
|
||||
return;
|
||||
}
|
||||
const cookieStr = typeof cookie === 'string' ? cookie : JSON.stringify(cookie);
|
||||
const envPath = path.join(__dirname, '.env');
|
||||
fs.writeFileSync(envPath, 'ALEXA_COOKIE=' + cookieStr + '\n');
|
||||
|
||||
console.log('\n==============================================');
|
||||
console.log(' 認証成功!');
|
||||
console.log('==============================================');
|
||||
console.log('.env を更新しました:', envPath);
|
||||
console.log('Cookie length:', cookieStr.length);
|
||||
}
|
||||
/**
|
||||
* auth3.js - メール/パスワードで直接認証(2FA なしのアカウント向け)
|
||||
*
|
||||
* 使い方:
|
||||
* AMAZON_EMAIL="xxx@xxx.com" AMAZON_PASSWORD="yourpass" node auth3.js
|
||||
*
|
||||
* 成功すると .env を更新して終了します。
|
||||
*/
|
||||
|
||||
const AlexaRemote = require('alexa-remote2');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
const email = process.env.AMAZON_EMAIL;
|
||||
const password = process.env.AMAZON_PASSWORD;
|
||||
|
||||
if (!email || !password) {
|
||||
console.error('[ERROR] 環境変数 AMAZON_EMAIL と AMAZON_PASSWORD を設定してください');
|
||||
console.error(' 例: AMAZON_EMAIL="xxx@xxx.com" AMAZON_PASSWORD="pass" node auth3.js');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
console.log(`[INFO] ${email} でログイン試行中...`);
|
||||
|
||||
const alexa = new AlexaRemote();
|
||||
|
||||
alexa.init(
|
||||
{
|
||||
email,
|
||||
password,
|
||||
alexaServiceHost: 'alexa.amazon.co.jp',
|
||||
amazonPage: 'amazon.co.jp',
|
||||
acceptLanguage: 'ja-JP',
|
||||
useWsMqtt: false,
|
||||
setupProxy: false,
|
||||
logger: (msg) => {
|
||||
if (!msg.includes('verbose') && !msg.includes('Bearer')) {
|
||||
console.log('[alexa]', msg);
|
||||
}
|
||||
},
|
||||
onSucess: (refreshedCookie) => {
|
||||
saveCookie(refreshedCookie, 'onSucess refresh');
|
||||
},
|
||||
},
|
||||
(err) => {
|
||||
if (err) {
|
||||
console.error('[ERROR] 認証失敗(詳細):', err);
|
||||
console.error('\n考えられる原因:');
|
||||
console.error(' - パスワードが違う');
|
||||
console.error(' - Amazon が CAPTCHA を要求している(後で再試行)');
|
||||
console.error(' - 2FA が実際は有効になっている');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// 認証成功
|
||||
const cookie = alexa.cookie;
|
||||
saveCookie(cookie, 'init success');
|
||||
process.exit(0);
|
||||
}
|
||||
);
|
||||
|
||||
function saveCookie(cookie, source) {
|
||||
if (!cookie) {
|
||||
console.error(`[${source}] Cookie が空です`);
|
||||
return;
|
||||
}
|
||||
const cookieStr = typeof cookie === 'string' ? cookie : JSON.stringify(cookie);
|
||||
const envPath = path.join(__dirname, '.env');
|
||||
fs.writeFileSync(envPath, 'ALEXA_COOKIE=' + cookieStr + '\n');
|
||||
|
||||
console.log('\n==============================================');
|
||||
console.log(' 認証成功!');
|
||||
console.log('==============================================');
|
||||
console.log('.env を更新しました:', envPath);
|
||||
console.log('Cookie length:', cookieStr.length);
|
||||
}
|
||||
|
||||
@@ -1,190 +1,190 @@
|
||||
/**
|
||||
* auth4.js - Amazon Japan OpenID フローを正しく再現するカスタム認証スクリプト
|
||||
* alexa-cookie2 の古いエンドポイント問題を回避して直接フォームを処理する
|
||||
*/
|
||||
|
||||
const https = require('https');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
const EMAIL = process.env.AMAZON_EMAIL;
|
||||
const PASSWORD = process.env.AMAZON_PASSWORD;
|
||||
|
||||
if (!EMAIL || !PASSWORD) {
|
||||
console.error('[ERROR] 環境変数 AMAZON_EMAIL と AMAZON_PASSWORD を設定してください');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const ALEXA_LOGIN_URL =
|
||||
'https://www.amazon.co.jp/ap/signin?' +
|
||||
new URLSearchParams({
|
||||
'openid.assoc_handle': 'amzn_dp_project_dee_jp',
|
||||
'openid.mode': 'checkid_setup',
|
||||
'openid.ns': 'http://specs.openid.net/auth/2.0',
|
||||
'openid.claimed_id': 'http://specs.openid.net/auth/2.0/identifier_select',
|
||||
'openid.identity': 'http://specs.openid.net/auth/2.0/identifier_select',
|
||||
'openid.return_to': 'https://alexa.amazon.co.jp/api/apps/v1/token',
|
||||
'pageId': 'amzn_dp_project_dee_jp',
|
||||
}).toString();
|
||||
|
||||
const USER_AGENT =
|
||||
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36';
|
||||
|
||||
let cookieJar = {};
|
||||
|
||||
function setCookies(setCookieHeaders) {
|
||||
if (!setCookieHeaders) return;
|
||||
const headers = Array.isArray(setCookieHeaders) ? setCookieHeaders : [setCookieHeaders];
|
||||
for (const h of headers) {
|
||||
const [kv] = h.split(';');
|
||||
const [k, v] = kv.trim().split('=');
|
||||
if (k && v !== undefined) cookieJar[k.trim()] = v.trim();
|
||||
}
|
||||
}
|
||||
|
||||
function getCookieHeader() {
|
||||
return Object.entries(cookieJar)
|
||||
.map(([k, v]) => `${k}=${v}`)
|
||||
.join('; ');
|
||||
}
|
||||
|
||||
function request(url, options = {}) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const parsed = new URL(url);
|
||||
const reqOpts = {
|
||||
hostname: parsed.hostname,
|
||||
path: parsed.pathname + parsed.search,
|
||||
method: options.method || 'GET',
|
||||
headers: {
|
||||
'User-Agent': USER_AGENT,
|
||||
'Accept-Language': 'ja-JP,ja;q=0.9',
|
||||
'Accept': 'text/html,application/xhtml+xml,*/*;q=0.8',
|
||||
'Cookie': getCookieHeader(),
|
||||
...(options.headers || {}),
|
||||
},
|
||||
};
|
||||
|
||||
const req = https.request(reqOpts, (res) => {
|
||||
setCookies(res.headers['set-cookie']);
|
||||
let body = '';
|
||||
res.on('data', (d) => (body += d));
|
||||
res.on('end', () => {
|
||||
resolve({ status: res.statusCode, headers: res.headers, body });
|
||||
});
|
||||
});
|
||||
req.on('error', reject);
|
||||
if (options.body) req.write(options.body);
|
||||
req.end();
|
||||
});
|
||||
}
|
||||
|
||||
// HTML の hidden フィールドを抽出
|
||||
function extractHiddenFields(html) {
|
||||
const fields = {};
|
||||
const re = /<input[^>]+type=["']?hidden["']?[^>]*>/gi;
|
||||
let match;
|
||||
while ((match = re.exec(html)) !== null) {
|
||||
const tag = match[0];
|
||||
const name = (tag.match(/name=["']([^"']+)["']/) || [])[1];
|
||||
const value = (tag.match(/value=["']([^"']*)["']/) || ['', ''])[1];
|
||||
if (name) fields[name] = value;
|
||||
}
|
||||
return fields;
|
||||
}
|
||||
|
||||
// フォームの action URL を抽出
|
||||
function extractFormAction(html) {
|
||||
const m = html.match(/id="ap_login_form"[^>]+action="([^"]+)"/);
|
||||
if (m) return m[1].replace(/&/g, '&');
|
||||
const m2 = html.match(/name="signIn"[^>]+action="([^"]+)"/);
|
||||
if (m2) return m2[1].replace(/&/g, '&');
|
||||
return null;
|
||||
}
|
||||
|
||||
async function main() {
|
||||
console.log('[1] ログインページ取得中...');
|
||||
const page1 = await request(ALEXA_LOGIN_URL);
|
||||
console.log(` Status: ${page1.status}, Cookies: ${Object.keys(cookieJar).join(', ')}`);
|
||||
|
||||
if (page1.status !== 200) {
|
||||
console.error(`[ERROR] ログインページ取得失敗: ${page1.status}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// フォーム情報を抽出
|
||||
const action = extractFormAction(page1.body);
|
||||
const hidden = extractHiddenFields(page1.body);
|
||||
|
||||
if (!action) {
|
||||
console.error('[ERROR] ログインフォームが見つかりません。HTMLを確認します:');
|
||||
console.error(page1.body.substring(0, 500));
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
console.log(`[2] フォーム送信先: ${action}`);
|
||||
console.log(` Hidden fields: ${Object.keys(hidden).join(', ')}`);
|
||||
|
||||
// フォームデータ構築
|
||||
const formData = new URLSearchParams({
|
||||
...hidden,
|
||||
email: EMAIL,
|
||||
password: PASSWORD,
|
||||
rememberMe: 'true',
|
||||
}).toString();
|
||||
|
||||
console.log('[3] 認証送信中...');
|
||||
const page2 = await request(action, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
'Referer': ALEXA_LOGIN_URL,
|
||||
},
|
||||
body: formData,
|
||||
});
|
||||
console.log(` Status: ${page2.status}`);
|
||||
console.log(` Location: ${page2.headers.location || '(none)'}`);
|
||||
console.log(` Cookies after login: ${Object.keys(cookieJar).join(', ')}`);
|
||||
|
||||
// リダイレクトをたどる
|
||||
let current = page2;
|
||||
let redirectCount = 0;
|
||||
while (current.status >= 300 && current.status < 400 && current.headers.location && redirectCount < 10) {
|
||||
const loc = current.headers.location;
|
||||
const nextUrl = loc.startsWith('http') ? loc : `https://www.amazon.co.jp${loc}`;
|
||||
console.log(`[${4 + redirectCount}] Redirect → ${nextUrl.substring(0, 80)}...`);
|
||||
current = await request(nextUrl);
|
||||
console.log(` Status: ${current.status}, New Cookies: ${Object.keys(cookieJar).join(', ')}`);
|
||||
redirectCount++;
|
||||
}
|
||||
|
||||
// 成功判定: at-acbjp または session-token が含まれているか
|
||||
const cookie = getCookieHeader();
|
||||
const hasAlexaToken = cookie.includes('at-acbjp') || cookie.includes('session-token');
|
||||
|
||||
if (!hasAlexaToken) {
|
||||
console.error('[ERROR] 認証に失敗しました。取得できたCookieに認証トークンが含まれていません。');
|
||||
console.error('取得済みCookieキー:', Object.keys(cookieJar).join(', '));
|
||||
if (current.body.includes('captcha') || current.body.includes('CAPTCHA')) {
|
||||
console.error('※ CAPTCHA が要求されています。しばらく待ってから再試行してください。');
|
||||
}
|
||||
if (current.body.includes('password') && current.body.includes('error')) {
|
||||
console.error('※ パスワードが間違っている可能性があります。');
|
||||
}
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// .env に保存
|
||||
const envPath = path.join(__dirname, '.env');
|
||||
fs.writeFileSync(envPath, `ALEXA_COOKIE=${cookie}\n`);
|
||||
|
||||
console.log('\n==============================================');
|
||||
console.log(' 認証成功!');
|
||||
console.log('==============================================');
|
||||
console.log(`.env を保存しました: ${envPath}`);
|
||||
console.log(`Cookie 長さ: ${cookie.length} 文字`);
|
||||
}
|
||||
|
||||
main().catch((err) => {
|
||||
console.error('[FATAL]', err);
|
||||
process.exit(1);
|
||||
});
|
||||
/**
|
||||
* auth4.js - Amazon Japan OpenID フローを正しく再現するカスタム認証スクリプト
|
||||
* alexa-cookie2 の古いエンドポイント問題を回避して直接フォームを処理する
|
||||
*/
|
||||
|
||||
const https = require('https');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
const EMAIL = process.env.AMAZON_EMAIL;
|
||||
const PASSWORD = process.env.AMAZON_PASSWORD;
|
||||
|
||||
if (!EMAIL || !PASSWORD) {
|
||||
console.error('[ERROR] 環境変数 AMAZON_EMAIL と AMAZON_PASSWORD を設定してください');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const ALEXA_LOGIN_URL =
|
||||
'https://www.amazon.co.jp/ap/signin?' +
|
||||
new URLSearchParams({
|
||||
'openid.assoc_handle': 'amzn_dp_project_dee_jp',
|
||||
'openid.mode': 'checkid_setup',
|
||||
'openid.ns': 'http://specs.openid.net/auth/2.0',
|
||||
'openid.claimed_id': 'http://specs.openid.net/auth/2.0/identifier_select',
|
||||
'openid.identity': 'http://specs.openid.net/auth/2.0/identifier_select',
|
||||
'openid.return_to': 'https://alexa.amazon.co.jp/api/apps/v1/token',
|
||||
'pageId': 'amzn_dp_project_dee_jp',
|
||||
}).toString();
|
||||
|
||||
const USER_AGENT =
|
||||
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36';
|
||||
|
||||
let cookieJar = {};
|
||||
|
||||
function setCookies(setCookieHeaders) {
|
||||
if (!setCookieHeaders) return;
|
||||
const headers = Array.isArray(setCookieHeaders) ? setCookieHeaders : [setCookieHeaders];
|
||||
for (const h of headers) {
|
||||
const [kv] = h.split(';');
|
||||
const [k, v] = kv.trim().split('=');
|
||||
if (k && v !== undefined) cookieJar[k.trim()] = v.trim();
|
||||
}
|
||||
}
|
||||
|
||||
function getCookieHeader() {
|
||||
return Object.entries(cookieJar)
|
||||
.map(([k, v]) => `${k}=${v}`)
|
||||
.join('; ');
|
||||
}
|
||||
|
||||
function request(url, options = {}) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const parsed = new URL(url);
|
||||
const reqOpts = {
|
||||
hostname: parsed.hostname,
|
||||
path: parsed.pathname + parsed.search,
|
||||
method: options.method || 'GET',
|
||||
headers: {
|
||||
'User-Agent': USER_AGENT,
|
||||
'Accept-Language': 'ja-JP,ja;q=0.9',
|
||||
'Accept': 'text/html,application/xhtml+xml,*/*;q=0.8',
|
||||
'Cookie': getCookieHeader(),
|
||||
...(options.headers || {}),
|
||||
},
|
||||
};
|
||||
|
||||
const req = https.request(reqOpts, (res) => {
|
||||
setCookies(res.headers['set-cookie']);
|
||||
let body = '';
|
||||
res.on('data', (d) => (body += d));
|
||||
res.on('end', () => {
|
||||
resolve({ status: res.statusCode, headers: res.headers, body });
|
||||
});
|
||||
});
|
||||
req.on('error', reject);
|
||||
if (options.body) req.write(options.body);
|
||||
req.end();
|
||||
});
|
||||
}
|
||||
|
||||
// HTML の hidden フィールドを抽出
|
||||
function extractHiddenFields(html) {
|
||||
const fields = {};
|
||||
const re = /<input[^>]+type=["']?hidden["']?[^>]*>/gi;
|
||||
let match;
|
||||
while ((match = re.exec(html)) !== null) {
|
||||
const tag = match[0];
|
||||
const name = (tag.match(/name=["']([^"']+)["']/) || [])[1];
|
||||
const value = (tag.match(/value=["']([^"']*)["']/) || ['', ''])[1];
|
||||
if (name) fields[name] = value;
|
||||
}
|
||||
return fields;
|
||||
}
|
||||
|
||||
// フォームの action URL を抽出
|
||||
function extractFormAction(html) {
|
||||
const m = html.match(/id="ap_login_form"[^>]+action="([^"]+)"/);
|
||||
if (m) return m[1].replace(/&/g, '&');
|
||||
const m2 = html.match(/name="signIn"[^>]+action="([^"]+)"/);
|
||||
if (m2) return m2[1].replace(/&/g, '&');
|
||||
return null;
|
||||
}
|
||||
|
||||
async function main() {
|
||||
console.log('[1] ログインページ取得中...');
|
||||
const page1 = await request(ALEXA_LOGIN_URL);
|
||||
console.log(` Status: ${page1.status}, Cookies: ${Object.keys(cookieJar).join(', ')}`);
|
||||
|
||||
if (page1.status !== 200) {
|
||||
console.error(`[ERROR] ログインページ取得失敗: ${page1.status}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// フォーム情報を抽出
|
||||
const action = extractFormAction(page1.body);
|
||||
const hidden = extractHiddenFields(page1.body);
|
||||
|
||||
if (!action) {
|
||||
console.error('[ERROR] ログインフォームが見つかりません。HTMLを確認します:');
|
||||
console.error(page1.body.substring(0, 500));
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
console.log(`[2] フォーム送信先: ${action}`);
|
||||
console.log(` Hidden fields: ${Object.keys(hidden).join(', ')}`);
|
||||
|
||||
// フォームデータ構築
|
||||
const formData = new URLSearchParams({
|
||||
...hidden,
|
||||
email: EMAIL,
|
||||
password: PASSWORD,
|
||||
rememberMe: 'true',
|
||||
}).toString();
|
||||
|
||||
console.log('[3] 認証送信中...');
|
||||
const page2 = await request(action, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
'Referer': ALEXA_LOGIN_URL,
|
||||
},
|
||||
body: formData,
|
||||
});
|
||||
console.log(` Status: ${page2.status}`);
|
||||
console.log(` Location: ${page2.headers.location || '(none)'}`);
|
||||
console.log(` Cookies after login: ${Object.keys(cookieJar).join(', ')}`);
|
||||
|
||||
// リダイレクトをたどる
|
||||
let current = page2;
|
||||
let redirectCount = 0;
|
||||
while (current.status >= 300 && current.status < 400 && current.headers.location && redirectCount < 10) {
|
||||
const loc = current.headers.location;
|
||||
const nextUrl = loc.startsWith('http') ? loc : `https://www.amazon.co.jp${loc}`;
|
||||
console.log(`[${4 + redirectCount}] Redirect → ${nextUrl.substring(0, 80)}...`);
|
||||
current = await request(nextUrl);
|
||||
console.log(` Status: ${current.status}, New Cookies: ${Object.keys(cookieJar).join(', ')}`);
|
||||
redirectCount++;
|
||||
}
|
||||
|
||||
// 成功判定: at-acbjp または session-token が含まれているか
|
||||
const cookie = getCookieHeader();
|
||||
const hasAlexaToken = cookie.includes('at-acbjp') || cookie.includes('session-token');
|
||||
|
||||
if (!hasAlexaToken) {
|
||||
console.error('[ERROR] 認証に失敗しました。取得できたCookieに認証トークンが含まれていません。');
|
||||
console.error('取得済みCookieキー:', Object.keys(cookieJar).join(', '));
|
||||
if (current.body.includes('captcha') || current.body.includes('CAPTCHA')) {
|
||||
console.error('※ CAPTCHA が要求されています。しばらく待ってから再試行してください。');
|
||||
}
|
||||
if (current.body.includes('password') && current.body.includes('error')) {
|
||||
console.error('※ パスワードが間違っている可能性があります。');
|
||||
}
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// .env に保存
|
||||
const envPath = path.join(__dirname, '.env');
|
||||
fs.writeFileSync(envPath, `ALEXA_COOKIE=${cookie}\n`);
|
||||
|
||||
console.log('\n==============================================');
|
||||
console.log(' 認証成功!');
|
||||
console.log('==============================================');
|
||||
console.log(`.env を保存しました: ${envPath}`);
|
||||
console.log(`Cookie 長さ: ${cookie.length} 文字`);
|
||||
}
|
||||
|
||||
main().catch((err) => {
|
||||
console.error('[FATAL]', err);
|
||||
process.exit(1);
|
||||
});
|
||||
|
||||
@@ -1,19 +1,19 @@
|
||||
services:
|
||||
alexa-api:
|
||||
build: .
|
||||
container_name: alexa_api
|
||||
restart: unless-stopped
|
||||
env_file:
|
||||
- .env
|
||||
environment:
|
||||
- PORT=3500
|
||||
networks:
|
||||
- windmill_windmill-internal
|
||||
# 外部には公開しない(Windmill ワーカーから内部ネットワーク経由でのみアクセス)
|
||||
# デバッグ時は以下のコメントを外す:
|
||||
# ports:
|
||||
# - "127.0.0.1:3500:3500"
|
||||
|
||||
networks:
|
||||
windmill_windmill-internal:
|
||||
external: true
|
||||
services:
|
||||
alexa-api:
|
||||
build: .
|
||||
container_name: alexa_api
|
||||
restart: unless-stopped
|
||||
env_file:
|
||||
- .env
|
||||
environment:
|
||||
- PORT=3500
|
||||
networks:
|
||||
- windmill_windmill-internal
|
||||
# 外部には公開しない(Windmill ワーカーから内部ネットワーク経由でのみアクセス)
|
||||
# デバッグ時は以下のコメントを外す:
|
||||
# ports:
|
||||
# - "127.0.0.1:3500:3500"
|
||||
|
||||
networks:
|
||||
windmill_windmill-internal:
|
||||
external: true
|
||||
|
||||
2514
alexa-api/package-lock.json
generated
2514
alexa-api/package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@@ -1,130 +1,130 @@
|
||||
/**
|
||||
* test_tts.js - TTS API テスト
|
||||
* node test_tts.js
|
||||
*/
|
||||
const https = require('https');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
const envContent = fs.readFileSync(path.join(__dirname, '.env'), 'utf8');
|
||||
const COOKIE_STR = envContent.match(/ALEXA_COOKIE=(.+)/)[1].trim();
|
||||
|
||||
function makeRequest(url, options = {}, extraCookies = '') {
|
||||
return new Promise((resolve, reject) => {
|
||||
const parsed = new URL(url);
|
||||
const allCookies = COOKIE_STR + (extraCookies ? '; ' + extraCookies : '');
|
||||
const reqOpts = {
|
||||
hostname: parsed.hostname,
|
||||
path: parsed.pathname + parsed.search,
|
||||
method: options.method || 'GET',
|
||||
headers: {
|
||||
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
|
||||
'Accept': 'application/json, text/plain, */*',
|
||||
'Accept-Language': 'ja-JP,ja;q=0.9',
|
||||
'Cookie': allCookies,
|
||||
...(options.headers || {}),
|
||||
},
|
||||
};
|
||||
const req = https.request(reqOpts, (res) => {
|
||||
let body = '';
|
||||
res.on('data', d => body += d);
|
||||
res.on('end', () => resolve({ status: res.statusCode, headers: res.headers, body }));
|
||||
});
|
||||
req.on('error', reject);
|
||||
if (options.body) req.write(options.body);
|
||||
req.end();
|
||||
});
|
||||
}
|
||||
|
||||
async function main() {
|
||||
// 1. CSRFトークン取得
|
||||
console.log('[1] CSRF token取得...');
|
||||
const langRes = await makeRequest('https://alexa.amazon.co.jp/api/language');
|
||||
const setCookies = langRes.headers['set-cookie'] || [];
|
||||
const csrfCookieStr = setCookies.find(c => c.startsWith('csrf='));
|
||||
const csrfToken = csrfCookieStr ? csrfCookieStr.split('=')[1].split(';')[0] : null;
|
||||
console.log(' CSRF token:', csrfToken);
|
||||
console.log(' Status:', langRes.status);
|
||||
|
||||
if (!csrfToken) { console.error('CSRF token not found!'); process.exit(1); }
|
||||
|
||||
// 2. デバイス一覧取得
|
||||
console.log('[2] デバイス一覧取得...');
|
||||
const devRes = await makeRequest('https://alexa.amazon.co.jp/api/devices-v2/device?cached=false');
|
||||
console.log(' Status:', devRes.status);
|
||||
const devices = JSON.parse(devRes.body).devices || [];
|
||||
console.log(' Device count:', devices.length);
|
||||
|
||||
// デバイス一覧表示
|
||||
devices.filter(d => d.deviceFamily !== 'TABLET').forEach(d => {
|
||||
console.log(` - ${d.accountName} (type=${d.deviceType}, serial=${d.serialNumber})`);
|
||||
});
|
||||
|
||||
// プレハブを探す
|
||||
const target = devices.find(d => d.serialNumber === 'G0922H08525302K5'); // オフィスの右エコー(以前成功したデバイス)
|
||||
console.log('\nTarget device:', target ? `${target.accountName}` : 'NOT FOUND');
|
||||
|
||||
if (!target) { process.exit(1); }
|
||||
|
||||
// 2.5. カスタマーIDを取得
|
||||
const bootstrapRes = await makeRequest('https://alexa.amazon.co.jp/api/bootstrap');
|
||||
const bootstrap = JSON.parse(bootstrapRes.body);
|
||||
const customerId = bootstrap.authentication?.customerId;
|
||||
console.log(' Customer ID:', customerId);
|
||||
|
||||
// 3. TTSリクエスト(新Cookie + Alexa.Speak + locale:'ja-JP' + 日本語テキスト)
|
||||
const sequenceObj = {
|
||||
'@type': 'com.amazon.alexa.behaviors.model.Sequence',
|
||||
startNode: {
|
||||
'@type': 'com.amazon.alexa.behaviors.model.OpaquePayloadOperationNode',
|
||||
type: 'Alexa.Speak',
|
||||
operationPayload: {
|
||||
deviceType: target.deviceType,
|
||||
deviceSerialNumber: target.serialNumber,
|
||||
customerId: customerId,
|
||||
locale: 'ja-JP',
|
||||
textToSpeak: '\u3053\u308c\u306f\u65e5\u672c\u8a9e\u306e\u30c6\u30b9\u30c8\u3067\u3059', // 「これは日本語のテストです」
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
// non-ASCII を \uXXXX に強制エスケープ
|
||||
// Amazon のパーサーが sequenceJson 内の raw UTF-8 を処理できない場合の回避策
|
||||
const rawSequenceJson = JSON.stringify(sequenceObj).replace(
|
||||
/[\u0080-\uffff]/g,
|
||||
c => '\\u' + ('0000' + c.charCodeAt(0).toString(16)).slice(-4)
|
||||
);
|
||||
const bodyObj = {
|
||||
behaviorId: 'PREVIEW',
|
||||
sequenceJson: rawSequenceJson,
|
||||
status: 'ENABLED',
|
||||
};
|
||||
const body = JSON.stringify(bodyObj);
|
||||
|
||||
console.log('\n[3] TTS送信...');
|
||||
// 送信内容確認(textToSpeakの部分が\uXXXXエスケープになっているか)
|
||||
const ttsIdx = body.indexOf('textToSpeak');
|
||||
console.log(' textToSpeak部分:', body.substring(ttsIdx, ttsIdx + 80));
|
||||
|
||||
|
||||
|
||||
const ttsRes = await makeRequest('https://alexa.amazon.co.jp/api/behaviors/preview', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'csrf': csrfToken,
|
||||
'Referer': 'https://alexa.amazon.co.jp/spa/index.html',
|
||||
'Origin': 'https://alexa.amazon.co.jp',
|
||||
},
|
||||
body,
|
||||
}, `csrf=${csrfToken}`);
|
||||
|
||||
console.log('TTS status:', ttsRes.status);
|
||||
console.log('TTS response:', ttsRes.body.substring(0, 500));
|
||||
|
||||
if (ttsRes.status === 200 || ttsRes.status === 202) {
|
||||
console.log('\n成功!エコーがしゃべるはずです。');
|
||||
}
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
/**
|
||||
* test_tts.js - TTS API テスト
|
||||
* node test_tts.js
|
||||
*/
|
||||
const https = require('https');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
const envContent = fs.readFileSync(path.join(__dirname, '.env'), 'utf8');
|
||||
const COOKIE_STR = envContent.match(/ALEXA_COOKIE=(.+)/)[1].trim();
|
||||
|
||||
function makeRequest(url, options = {}, extraCookies = '') {
|
||||
return new Promise((resolve, reject) => {
|
||||
const parsed = new URL(url);
|
||||
const allCookies = COOKIE_STR + (extraCookies ? '; ' + extraCookies : '');
|
||||
const reqOpts = {
|
||||
hostname: parsed.hostname,
|
||||
path: parsed.pathname + parsed.search,
|
||||
method: options.method || 'GET',
|
||||
headers: {
|
||||
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
|
||||
'Accept': 'application/json, text/plain, */*',
|
||||
'Accept-Language': 'ja-JP,ja;q=0.9',
|
||||
'Cookie': allCookies,
|
||||
...(options.headers || {}),
|
||||
},
|
||||
};
|
||||
const req = https.request(reqOpts, (res) => {
|
||||
let body = '';
|
||||
res.on('data', d => body += d);
|
||||
res.on('end', () => resolve({ status: res.statusCode, headers: res.headers, body }));
|
||||
});
|
||||
req.on('error', reject);
|
||||
if (options.body) req.write(options.body);
|
||||
req.end();
|
||||
});
|
||||
}
|
||||
|
||||
async function main() {
|
||||
// 1. CSRFトークン取得
|
||||
console.log('[1] CSRF token取得...');
|
||||
const langRes = await makeRequest('https://alexa.amazon.co.jp/api/language');
|
||||
const setCookies = langRes.headers['set-cookie'] || [];
|
||||
const csrfCookieStr = setCookies.find(c => c.startsWith('csrf='));
|
||||
const csrfToken = csrfCookieStr ? csrfCookieStr.split('=')[1].split(';')[0] : null;
|
||||
console.log(' CSRF token:', csrfToken);
|
||||
console.log(' Status:', langRes.status);
|
||||
|
||||
if (!csrfToken) { console.error('CSRF token not found!'); process.exit(1); }
|
||||
|
||||
// 2. デバイス一覧取得
|
||||
console.log('[2] デバイス一覧取得...');
|
||||
const devRes = await makeRequest('https://alexa.amazon.co.jp/api/devices-v2/device?cached=false');
|
||||
console.log(' Status:', devRes.status);
|
||||
const devices = JSON.parse(devRes.body).devices || [];
|
||||
console.log(' Device count:', devices.length);
|
||||
|
||||
// デバイス一覧表示
|
||||
devices.filter(d => d.deviceFamily !== 'TABLET').forEach(d => {
|
||||
console.log(` - ${d.accountName} (type=${d.deviceType}, serial=${d.serialNumber})`);
|
||||
});
|
||||
|
||||
// プレハブを探す
|
||||
const target = devices.find(d => d.serialNumber === 'G0922H08525302K5'); // オフィスの右エコー(以前成功したデバイス)
|
||||
console.log('\nTarget device:', target ? `${target.accountName}` : 'NOT FOUND');
|
||||
|
||||
if (!target) { process.exit(1); }
|
||||
|
||||
// 2.5. カスタマーIDを取得
|
||||
const bootstrapRes = await makeRequest('https://alexa.amazon.co.jp/api/bootstrap');
|
||||
const bootstrap = JSON.parse(bootstrapRes.body);
|
||||
const customerId = bootstrap.authentication?.customerId;
|
||||
console.log(' Customer ID:', customerId);
|
||||
|
||||
// 3. TTSリクエスト(新Cookie + Alexa.Speak + locale:'ja-JP' + 日本語テキスト)
|
||||
const sequenceObj = {
|
||||
'@type': 'com.amazon.alexa.behaviors.model.Sequence',
|
||||
startNode: {
|
||||
'@type': 'com.amazon.alexa.behaviors.model.OpaquePayloadOperationNode',
|
||||
type: 'Alexa.Speak',
|
||||
operationPayload: {
|
||||
deviceType: target.deviceType,
|
||||
deviceSerialNumber: target.serialNumber,
|
||||
customerId: customerId,
|
||||
locale: 'ja-JP',
|
||||
textToSpeak: '\u3053\u308c\u306f\u65e5\u672c\u8a9e\u306e\u30c6\u30b9\u30c8\u3067\u3059', // 「これは日本語のテストです」
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
// non-ASCII を \uXXXX に強制エスケープ
|
||||
// Amazon のパーサーが sequenceJson 内の raw UTF-8 を処理できない場合の回避策
|
||||
const rawSequenceJson = JSON.stringify(sequenceObj).replace(
|
||||
/[\u0080-\uffff]/g,
|
||||
c => '\\u' + ('0000' + c.charCodeAt(0).toString(16)).slice(-4)
|
||||
);
|
||||
const bodyObj = {
|
||||
behaviorId: 'PREVIEW',
|
||||
sequenceJson: rawSequenceJson,
|
||||
status: 'ENABLED',
|
||||
};
|
||||
const body = JSON.stringify(bodyObj);
|
||||
|
||||
console.log('\n[3] TTS送信...');
|
||||
// 送信内容確認(textToSpeakの部分が\uXXXXエスケープになっているか)
|
||||
const ttsIdx = body.indexOf('textToSpeak');
|
||||
console.log(' textToSpeak部分:', body.substring(ttsIdx, ttsIdx + 80));
|
||||
|
||||
|
||||
|
||||
const ttsRes = await makeRequest('https://alexa.amazon.co.jp/api/behaviors/preview', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'csrf': csrfToken,
|
||||
'Referer': 'https://alexa.amazon.co.jp/spa/index.html',
|
||||
'Origin': 'https://alexa.amazon.co.jp',
|
||||
},
|
||||
body,
|
||||
}, `csrf=${csrfToken}`);
|
||||
|
||||
console.log('TTS status:', ttsRes.status);
|
||||
console.log('TTS response:', ttsRes.body.substring(0, 500));
|
||||
|
||||
if (ttsRes.status === 200 || ttsRes.status === 202) {
|
||||
console.log('\n成功!エコーがしゃべるはずです。');
|
||||
}
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
|
||||
Reference in New Issue
Block a user