feat(auth): add WeChat mini program login endpoint
Add jscode2session exchange, CSRF bypass for servicewechat.com, and openid-based auto register/login for the mini program client. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -0,0 +1,59 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { exchangeMiniProgramCode, loadWechatMiniappConfig } from './wechat-miniapp.mjs';
|
||||
|
||||
test('loadWechatMiniappConfig prefers miniapp-specific env vars', () => {
|
||||
const config = loadWechatMiniappConfig({
|
||||
H5_WECHAT_MINIAPP_APP_ID: 'wx-mini',
|
||||
H5_WECHAT_MINIAPP_APP_SECRET: 'secret-mini',
|
||||
H5_WECHAT_APP_ID: 'wx-other',
|
||||
H5_WECHAT_APP_SECRET: 'secret-other',
|
||||
});
|
||||
assert.equal(config.enabled, true);
|
||||
assert.equal(config.appId, 'wx-mini');
|
||||
assert.equal(config.appSecret, 'secret-mini');
|
||||
});
|
||||
|
||||
test('exchangeMiniProgramCode calls jscode2session and returns openid', async () => {
|
||||
const calls = [];
|
||||
const result = await exchangeMiniProgramCode({
|
||||
appId: 'wxtest',
|
||||
appSecret: 'secret',
|
||||
code: 'abc123',
|
||||
fetchImpl: async (url) => {
|
||||
calls.push(String(url));
|
||||
return {
|
||||
ok: true,
|
||||
async json() {
|
||||
return { openid: 'openid-1', session_key: 'sk', unionid: 'union-1' };
|
||||
},
|
||||
};
|
||||
},
|
||||
});
|
||||
assert.equal(result.openid, 'openid-1');
|
||||
assert.equal(result.unionid, 'union-1');
|
||||
assert.match(calls[0], /jscode2session\?/);
|
||||
assert.match(calls[0], /js_code=abc123/);
|
||||
});
|
||||
|
||||
test('exchangeMiniProgramCode surfaces WeChat errcode', async () => {
|
||||
await assert.rejects(
|
||||
() =>
|
||||
exchangeMiniProgramCode({
|
||||
appId: 'wxtest',
|
||||
appSecret: 'secret',
|
||||
code: 'bad',
|
||||
fetchImpl: async () => ({
|
||||
ok: true,
|
||||
async json() {
|
||||
return { errcode: 40029, errmsg: 'invalid code' };
|
||||
},
|
||||
}),
|
||||
}),
|
||||
(error) => {
|
||||
assert.equal(error.code, 'wechat_miniapp_code_failed');
|
||||
assert.match(error.message, /invalid code/);
|
||||
return true;
|
||||
},
|
||||
);
|
||||
});
|
||||
Reference in New Issue
Block a user