feat: update MCP config and TOOLS.md with calendar/contacts note

This commit is contained in:
root
2026-03-29 18:45:26 +08:00
parent 1a9fdc7274
commit c3e845f89c
3427 changed files with 2447281 additions and 1 deletions

View File

@@ -0,0 +1,21 @@
# 项目规范
## 发布流程
用户要求发布代码时,自动执行以下步骤:
1. **重构文档** - 更新 README.md 和 SKILL.md确保与当前功能一致
2. **更新 package.json** - 递增 version遵循 semver更新 description 与功能匹配
3. **提交并发布** - git add/commit/push 到 GitHub然后 `clawhub publish` 发布到 ClawHub
## ClawHub 发布命令
```bash
clawhub publish /Users/ogenes/Data/www/dingtalk-api --slug dingtalk-api --name "DingTalk API" --version <新版本号> --changelog "<变更说明>"
```
## 技术栈
- TypeScript + ts-node
- @alicloud/dingtalk SDK
- 每个脚本文件开头需要 `export {};` 以避免跨文件类型冲突

View File

@@ -0,0 +1,688 @@
# DingTalk API Skill
[![ClawHub](https://img.shields.io/badge/ClawHub-已发布-blue)](https://clawhub.com/ogenes/dingtalk-api)
钉钉开放平台 API 调用技能,支持用户搜索/详情/查询、部门管理(搜索/详情/子部门/用户列表/父部门)、机器人单聊/群聊消息发送、群内机器人列表查询、离职记录查询、OA审批管理查询/发起/审批/转交/评论)等功能。
> **已发布到 [ClawHub](https://clawhub.com/ogenes/dingtalk-api)**,可通过 `clawhub install dingtalk-api` 一键安装。
## 功能特性
### 用户管理
- **用户搜索** - 根据姓名搜索用户,返回 UserId 列表
- **用户详情** - 获取指定用户的详细信息
- **用户所属部门** - 获取指定用户的所有父部门列表
- **手机号查用户** - 根据手机号查询用户 userid
- **unionid查用户** - 根据 unionid 查询用户 userid
- **员工人数** - 获取企业员工总数(可选仅已激活)
- **未登录用户** - 获取未登录钉钉的员工列表
- **离职记录** - 查询离职员工记录列表
### 部门管理
- **部门搜索** - 根据名称搜索部门,返回部门 ID 列表
- **部门详情** - 获取指定部门的详细信息
- **父部门列表** - 获取指定部门的所有父部门列表
- **子部门列表** - 获取指定部门下的子部门 ID 列表
- **部门用户列表** - 获取指定部门下的用户列表
- **部门用户ID列表** - 获取指定部门下所有用户的 userid 列表
### 消息与机器人
- **单聊消息** - 通过机器人向指定用户发送单聊消息
- **群聊消息** - 通过机器人向指定群会话发送消息
- **机器人列表** - 查询群内已配置的机器人列表
### OA审批管理
- **审批实例 ID 列表** - 获取指定审批模板在时间段内的实例 ID 列表
- **审批实例详情** - 获取单个审批实例的详细信息
- **用户发起审批** - 获取用户发起的审批列表
- **抄送用户审批** - 获取抄送用户的审批列表
- **待处理审批** - 获取用户待处理的审批列表
- **已处理审批** - 获取用户已处理的审批列表
- **待审批数量** - 获取用户待审批任务数量
- **发起审批** - 创建新的审批实例
- **终止审批** - 撤销/终止审批实例
- **执行任务** - 同意或拒绝审批任务
- **转交任务** - 将审批任务转交给其他用户
- **添加评论** - 为审批实例添加评论
### 技术特性
- **自动认证** - 自动获取 access_token无需手动管理
- **TypeScript** - 类型安全,代码提示友好
## 安装方式
### 方式一:通过 ClawHub 安装(推荐)
```bash
npm install -g clawhub
clawhub install dingtalk-api
```
### 方式二:通过 Git 安装
```bash
git clone https://github.com/ogenes/dingtalk-api.git
cd dingtalk-api
npm install
```
## 配置环境变量
```bash
export DINGTALK_APP_KEY="<your-app-key>"
export DINGTALK_APP_SECRET="<your-app-secret>"
```
## 使用方法
### 1. 搜索用户
```bash
npm run search-user -- "张三"
```
输出:
```json
{
"success": true,
"keyword": "张三",
"totalCount": 3,
"hasMore": false,
"userIds": ["123456789", "987654321", "456789123"]
}
```
### 2. 搜索部门
```bash
npm run search-department -- "技术部"
```
输出:
```json
{
"success": true,
"keyword": "技术部",
"totalCount": 2,
"hasMore": false,
"departmentIds": [12345, 67890]
}
```
### 3. 获取部门详情
```bash
npm run get-department -- 12345
```
输出:
```json
{
"success": true,
"department": {
"deptId": 12345,
"name": "技术部",
"parentId": 1
}
}
```
### 4. 获取子部门列表
```bash
npm run list-sub-departments -- 1
```
输出:
```json
{
"success": true,
"deptId": 1,
"subDepartmentIds": [12345, 67890, 11111]
}
```
### 5. 获取部门用户列表
```bash
npm run list-department-users -- 12345
```
输出:
```json
{
"success": true,
"deptId": 12345,
"users": [
{ "userId": "user001", "name": "张三" },
{ "userId": "user002", "name": "李四" }
]
}
```
### 6. 发送单聊消息
```bash
npm run send-user-message -- "<userId>" "<robotCode>" "你好"
```
输出:
```json
{
"success": true,
"userId": "123456",
"robotCode": "robot_code",
"processQueryKey": "query_key",
"flowControlledStaffIdList": [],
"invalidStaffIdList": [],
"message": "你好"
}
```
### 7. 发送群聊消息
```bash
npm run send-group-message -- "<openConversationId>" "<robotCode>" "大家好"
```
输出:
```json
{
"success": true,
"openConversationId": "cid",
"robotCode": "robot_code",
"processQueryKey": "query_key",
"message": "大家好"
}
```
### 8. 获取群内机器人列表
```bash
npm run get-bot-list -- "<openConversationId>"
```
输出:
```json
{
"success": true,
"openConversationId": "cid",
"botList": [
{
"robotCode": "code",
"robotName": "name",
"robotAvatar": "url",
"openRobotType": 1
}
]
}
```
所有命令支持 `--debug` 参数查看完整 API 响应。
### 9. 获取审批实例 ID 列表
```bash
npm run list-approval-instance-ids -- "PROC-XXX" --startTime 1704067200000 --endTime 1706745600000
```
输出:
```json
{
"success": true,
"processCode": "PROC-XXX",
"instanceIds": ["xxx-123", "xxx-456"],
"totalCount": 2,
"hasMore": false
}
```
### 10. 获取审批实例详情
```bash
npm run get-approval-instance -- "xxx-123"
```
输出:
```json
{
"success": true,
"instanceId": "xxx-123",
"instance": {
"processInstanceId": "xxx-123",
"title": "请假申请",
"createTimeGMT": "2024-01-01T00:00:00Z",
"originatorUserId": "user001",
"status": "COMPLETED",
"formComponentValues": [...]
}
}
```
### 11. 获取用户发起的审批列表
```bash
npm run list-user-initiated-approvals -- "user001" --startTime 1704067200000 --endTime 1706745600000
```
输出:
```json
{
"success": true,
"userId": "user001",
"instances": [...],
"totalCount": 5,
"hasMore": false
}
```
### 12. 获取用户待处理审批列表
```bash
npm run list-user-todo-approvals -- "user001"
```
输出:
```json
{
"success": true,
"userId": "user001",
"instances": [...],
"totalCount": 3,
"hasMore": false
}
```
### 13. 获取用户待审批数量
```bash
npm run get-user-todo-count -- "user001"
```
输出:
```json
{
"success": true,
"userId": "user001",
"count": 5
}
```
### 14. 发起审批实例
```bash
npm run create-approval-instance -- "PROC-XXX" "user001" "1" '[{"name":"标题","value":"测试审批"}]'
```
输出:
```json
{
"success": true,
"processCode": "PROC-XXX",
"originatorUserId": "user001",
"instanceId": "xxx-new"
}
```
### 15. 终止审批实例
```bash
npm run terminate-approval-instance -- "xxx-123" "user001" --remark "撤销原因"
```
输出:
```json
{
"success": true,
"instanceId": "xxx-123",
"message": "审批实例已终止"
}
```
### 16. 执行审批任务(同意/拒绝)
```bash
npm run execute-approval-task -- "xxx-123" "user001" "agree" --remark "同意"
npm run execute-approval-task -- "xxx-123" "user001" "refuse" --remark "拒绝原因"
```
输出:
```json
{
"success": true,
"instanceId": "xxx-123",
"userId": "user001",
"action": "agree",
"message": "已同意审批"
}
```
### 17. 转交审批任务
```bash
npm run transfer-approval-task -- "xxx-123" "user001" "user002" --remark "转交给他人处理"
```
输出:
```json
{
"success": true,
"instanceId": "xxx-123",
"userId": "user001",
"transferToUserId": "user002",
"message": "审批任务已转交"
}
```
### 18. 添加审批评论
```bash
npm run add-approval-comment -- "xxx-123" "user001" "这是一条评论"
```
输出:
```json
{
"success": true,
"instanceId": "xxx-123",
"userId": "user001",
"message": "评论已添加"
}
```
### 19. 获取用户详情
```bash
npm run get-user -- "user001"
```
输出:
```json
{
"success": true,
"user": {
"userid": "user001",
"name": "张三",
"mobile": "138****1234",
"email": "zhangsan@example.com",
"dept_id_list": [12345, 67890]
}
}
```
### 10. 获取用户父部门列表
```bash
npm run list-user-parent-departments -- "user001"
```
输出:
```json
{
"success": true,
"userId": "user001",
"parentIdList": [12345, 67890, 1]
}
```
### 11. 获取部门父部门列表
```bash
npm run list-department-parents -- 12345
```
输出:
```json
{
"success": true,
"deptId": 12345,
"parentIdList": [12345, 67890, 1]
}
```
### 12. 获取部门用户ID列表
```bash
npm run list-department-user-ids -- 12345
```
输出:
```json
{
"success": true,
"deptId": 12345,
"userIds": ["user001", "user002", "user003"]
}
```
### 13. 获取部门用户详情(分页)
```bash
npm run list-department-user-details -- 12345 --cursor 0 --size 50
```
输出:
```json
{
"success": true,
"deptId": 12345,
"users": [
{ "userid": "user001", "name": "张三" },
{ "userid": "user002", "name": "李四" }
],
"hasMore": true,
"nextCursor": 100
}
```
### 14. 获取员工人数
```bash
npm run get-user-count
npm run get-user-count -- --onlyActive
```
输出:
```json
{
"success": true,
"onlyActive": false,
"count": 150
}
```
### 15. 根据手机号查询用户
```bash
npm run get-user-by-mobile -- "13800138000"
```
输出:
```json
{
"success": true,
"mobile": "13800138000",
"userId": "user001"
}
```
### 16. 根据 unionid 查询用户
```bash
npm run get-user-by-unionid -- "xxxxx"
```
输出:
```json
{
"success": true,
"unionid": "xxxxx",
"userId": "user001"
}
```
### 17. 获取未登录用户列表
```bash
npm run list-inactive-users -- "20240115" --deptIds "12345,67890" --offset 0 --size 100
```
输出:
```json
{
"success": true,
"queryDate": "20240115",
"userIds": ["user001", "user002"],
"hasMore": false
}
```
### 18. 查询离职记录列表
```bash
npm run list-resigned-users -- "2024-01-01T00:00:00+08:00" "2024-02-01T00:00:00+08:00"
```
输出:
```json
{
"success": true,
"startTime": "2024-01-01T00:00:00+08:00",
"endTime": "2024-02-01T00:00:00+08:00",
"records": [
{
"userId": "user001",
"name": "张三",
"leaveTime": "2024-01-15T10:00:00Z",
"leaveReason": "个人原因"
}
]
}
```
## 前置要求
1. **钉钉应用**
- 在 [钉钉开放平台](https://open.dingtalk.com/) 创建企业内部应用
- 添加权限:通讯录搜索、通讯录部门信息读权限、机器人发送消息等
- 获取 **AppKey****AppSecret**
2. **环境**
- Node.js >= 16
## 项目结构
```
dingtalk-api/
├── scripts/
│ ├── search-user.ts # 用户搜索
│ ├── get-user.ts # 用户详情
│ ├── list-user-parent-departments.ts # 用户父部门列表
│ ├── get-user-by-mobile.ts # 手机号查用户
│ ├── get-user-by-unionid.ts # unionid查用户
│ ├── get-user-count.ts # 员工人数
│ ├── list-inactive-users.ts # 未登录用户列表
│ ├── list-resigned-users.ts # 离职记录列表
│ ├── search-department.ts # 部门搜索
│ ├── get-department.ts # 部门详情
│ ├── list-department-parents.ts # 部门父部门列表
│ ├── list-sub-departments.ts # 子部门列表
│ ├── list-department-users.ts # 部门用户列表
│ ├── list-department-user-ids.ts # 部门用户ID列表
│ ├── list-department-user-details.ts # 部门用户详情(分页)
│ ├── send-user-message.ts # 单聊消息发送
│ ├── send-group-message.ts # 群聊消息发送
│ ├── get-bot-list.ts # 群内机器人列表
│ ├── list-approval-instance-ids.ts # 审批实例 ID 列表
│ ├── get-approval-instance.ts # 审批实例详情
│ ├── list-user-initiated-approvals.ts # 用户发起审批列表
│ ├── list-user-cc-approvals.ts # 抄送用户审批列表
│ ├── list-user-todo-approvals.ts # 待处理审批列表
│ ├── list-user-done-approvals.ts # 已处理审批列表
│ ├── get-user-todo-count.ts # 待审批数量
│ ├── create-approval-instance.ts # 发起审批
│ ├── terminate-approval-instance.ts # 终止审批
│ ├── execute-approval-task.ts # 执行审批任务
│ ├── transfer-approval-task.ts # 转交审批任务
│ └── add-approval-comment.ts # 添加审批评论
├── types/
│ └── dingtalk.d.ts # 钉钉 SDK 类型定义
├── SKILL.md # Skill 文档
├── README.md
├── package.json
└── tsconfig.json
```
## API 文档
### 用户管理
- [搜索用户](https://open.dingtalk.com/document/orgapp/you-can-call-this-operation-to-query-users)
- [查询用户详情](https://open.dingtalk.com/document/orgapp/query-user-details)
- [查询部门用户父部门路径](https://open.dingtalk.com/document/orgapp/query-the-parent-department-path-of-a-department-user)
- [查询指定用户的所有父部门列表](https://open.dingtalk.com/document/orgapp/query-the-list-of-all-parent-departments-of-a-specified-user)
- [根据手机号获取用户信息](https://open.dingtalk.com/document/orgapp/query-users-by-phone-number)
- [根据unionid获取userid](https://open.dingtalk.com/document/orgapp/query-a-user-by-the-unionid)
- [获取员工人数](https://open.dingtalk.com/document/orgapp/obtain-the-number-of-employees-v2)
- [查询企业未登录钉钉的员工列表](https://open.dingtalk.com/document/orgapp/queries-the-list-of-employees-who-have-not-logged-on-to-dingtalk)
- [查询离职记录列表](https://open.dingtalk.com/document/isvapp-server/employee_resignation_records)
### 部门管理
- [搜索部门](https://open.dingtalk.com/document/orgapp/search-department)
- [获取部门详情](https://open.dingtalk.com/document/orgapp/query-department-details0-v2)
- [获取指定部门的所有父部门列表](https://open.dingtalk.com/document/orgapp/obtain-the-list-of-all-parent-departments-of-a-department)
- [获取子部门 ID 列表](https://open.dingtalk.com/document/orgapp/obtain-a-sub-department-id-list-v2)
- [获取部门用户基础信息](https://open.dingtalk.com/document/orgapp/queries-the-simple-information-of-a-department-user)
- [获取部门用户userid列表](https://open.dingtalk.com/document/orgapp/obtain-the-list-of-department-userids)
### 消息与机器人
- [机器人发送单聊消息](https://open.dingtalk.com/document/orgapp/chatbots-send-one-on-one-chat-messages-in-batches)
- [机器人发送群消息](https://open.dingtalk.com/document/orgapp/the-robot-sends-a-group-message)
- [获取群内机器人列表](https://open.dingtalk.com/document/orgapp/obtain-the-list-of-robots-in-the-group)
### 认证
- [获取企业内部应用的 accessToken](https://open.dingtalk.com/document/orgapp/obtain-the-access_token-of-an-internal-app)
### OA审批
- [获取审批实例ID列表](https://open.dingtalk.com/document/isvapp-server/obtain-the-list-of-approval-instance-ids)
- [获取单个审批实例详情](https://open.dingtalk.com/document/isvapp-server/get-details-of-a-single-approval-instance)
- [获取用户待审批数量](https://open.dingtalk.com/document/isvapp-server/obtains-the-number-of-to-dos-for-a-user)
- [获取用户已发起审批列表](https://open.dingtalk.com/document/isvapp-server/get-user-initiated-approval-list)
- [获取用户待处理审批列表](https://open.dingtalk.com/document/isvapp-server/get-user-to-do-approval-list)
- [获取用户已处理审批列表](https://open.dingtalk.com/document/isvapp-server/get-user-processed-approval-list)
- [获取用户抄送审批列表](https://open.dingtalk.com/document/isvapp-server/get-list-of-approval-copied-to-user)
- [创建审批实例](https://open.dingtalk.com/document/isvapp-server/create-an-approval-instance)
- [撤销审批实例](https://open.dingtalk.com/document/isvapp-server/cancel-an-approval-instance)
- [执行审批操作](https://open.dingtalk.com/document/isvapp-server/execute-approval-operation)
- [添加审批评论](https://open.dingtalk.com/document/isvapp-server/add-approval-comments)
## 许可证
MIT

View File

@@ -0,0 +1,644 @@
---
name: dingtalk-api
description: 调用钉钉开放平台API支持用户搜索/详情/查询、部门管理(搜索/详情/子部门/用户列表/父部门、机器人单聊消息发送、群聊消息发送、群内机器人列表查询、离职记录查询。Use when needing to search DingTalk users or departments, get user/department details, send robot messages, list group bots, or query resigned employees.
---
# DingTalk API Skill
用于调用钉钉开放平台 API 的技能,支持用户搜索/详情/查询、部门管理(搜索/详情/子部门/用户列表/父部门、机器人消息发送、群内机器人查询、离职记录查询、OA审批管理查询/发起/审批/转交/评论)等功能。
## 前置要求
- 已设置环境变量 `DINGTALK_APP_KEY``DINGTALK_APP_SECRET`
- 钉钉应用已创建并拥有相应 API 权限
## 环境变量配置
```bash
export DINGTALK_APP_KEY="<your-app-key>"
export DINGTALK_APP_SECRET="<your-app-secret>"
```
## 功能列表
### 1. 搜索用户 (search-user)
根据姓名搜索用户,返回匹配的 UserId 列表。
```bash
npx ts-node scripts/search-user.ts "<搜索关键词>"
```
输出:
```json
{
"success": true,
"keyword": "张三",
"totalCount": 3,
"hasMore": false,
"userIds": ["123456789", "987654321"]
}
```
### 2. 搜索部门 (search-department)
根据名称搜索部门,返回匹配的部门 ID 列表。
```bash
npx ts-node scripts/search-department.ts "<搜索关键词>" [--debug]
```
输出:
```json
{
"success": true,
"keyword": "技术部",
"totalCount": 2,
"hasMore": false,
"departmentIds": [12345, 67890]
}
```
### 3. 获取部门详情 (get-department)
获取指定部门的详细信息。
```bash
npx ts-node scripts/get-department.ts <deptId> [--debug]
```
输出:
```json
{
"success": true,
"department": {
"deptId": 12345,
"name": "技术部",
"parentId": 1
}
}
```
### 4. 获取子部门列表 (list-sub-departments)
获取指定部门下的子部门 ID 列表。根部门 deptId 为 1。
```bash
npx ts-node scripts/list-sub-departments.ts <deptId> [--debug]
```
输出:
```json
{
"success": true,
"deptId": 1,
"subDepartmentIds": [12345, 67890, 11111]
}
```
### 5. 获取部门用户列表 (list-department-users)
获取指定部门下的用户列表userId + 姓名),自动分页获取全部用户。
```bash
npx ts-node scripts/list-department-users.ts <deptId> [--debug]
```
输出:
```json
{
"success": true,
"deptId": 12345,
"users": [
{ "userId": "user001", "name": "张三" },
{ "userId": "user002", "name": "李四" }
]
}
```
### 6. 发送单聊消息 (send-user-message)
通过机器人向指定用户发送单聊消息。
```bash
npx ts-node scripts/send-user-message.ts "<userId>" "<robotCode>" "<消息内容>" [--debug]
```
输出:
```json
{
"success": true,
"userId": "123456",
"robotCode": "robot_code",
"processQueryKey": "query_key",
"flowControlledStaffIdList": [],
"invalidStaffIdList": [],
"message": "消息内容"
}
```
### 7. 发送群聊消息 (send-group-message)
通过机器人向指定群会话发送消息。
```bash
npx ts-node scripts/send-group-message.ts "<openConversationId>" "<robotCode>" "<消息内容>" [--debug]
```
输出:
```json
{
"success": true,
"openConversationId": "cid",
"robotCode": "robot_code",
"processQueryKey": "query_key",
"message": "消息内容"
}
```
### 8. 获取群内机器人列表 (get-bot-list)
查询群内已配置的机器人列表。
```bash
npx ts-node scripts/get-bot-list.ts "<openConversationId>" [--debug]
```
输出:
```json
{
"success": true,
"openConversationId": "cid",
"botList": [
{
"robotCode": "code",
"robotName": "name",
"robotAvatar": "url",
"openRobotType": 1
}
]
}
```
### 9. 查询用户详情 (get-user)
获取指定用户的详细信息,包括姓名、手机号、邮箱、部门列表等。
```bash
npx ts-node scripts/get-user.ts "<userId>" [--debug]
```
输出:
```json
{
"success": true,
"user": {
"userid": "user001",
"name": "张三",
"mobile": "138****1234",
"email": "zhangsan@example.com",
"dept_id_list": [12345, 67890]
}
}
```
### 10. 获取用户父部门列表 (list-user-parent-departments)
获取指定用户所属的所有父部门列表,从直接部门到根部门。
```bash
npx ts-node scripts/list-user-parent-departments.ts "<userId>" [--debug]
```
输出:
```json
{
"success": true,
"userId": "user001",
"parentIdList": [12345, 67890, 1]
}
```
### 11. 获取部门父部门列表 (list-department-parents)
获取指定部门的所有父部门列表,第一个是自身,最后一个是根部门。
```bash
npx ts-node scripts/list-department-parents.ts <deptId> [--debug]
```
输出:
```json
{
"success": true,
"deptId": 12345,
"parentIdList": [12345, 67890, 1]
}
```
### 12. 获取部门用户ID列表 (list-department-user-ids)
获取指定部门下所有用户的 userid 列表。
```bash
npx ts-node scripts/list-department-user-ids.ts <deptId> [--debug]
```
输出:
```json
{
"success": true,
"deptId": 12345,
"userIds": ["user001", "user002", "user003"]
}
```
### 13. 获取部门用户详情分页版 (list-department-user-details)
分页获取部门用户详细信息,支持自定义 cursor 和 size。
```bash
npx ts-node scripts/list-department-user-details.ts <deptId> [--cursor <cursor>] [--size <size>] [--debug]
```
输出:
```json
{
"success": true,
"deptId": 12345,
"users": [
{ "userid": "user001", "name": "张三" },
{ "userid": "user002", "name": "李四" }
],
"hasMore": true,
"nextCursor": 100
}
```
### 14. 获取员工人数 (get-user-count)
获取企业员工总数,可选择是否仅统计已激活员工。
```bash
npx ts-node scripts/get-user-count.ts [--onlyActive] [--debug]
```
输出:
```json
{
"success": true,
"onlyActive": false,
"count": 150
}
```
### 15. 根据手机号查询用户 (get-user-by-mobile)
根据手机号查询用户 userid。仅企业内部应用可用只能查询在职员工。
```bash
npx ts-node scripts/get-user-by-mobile.ts "<mobile>" [--debug]
```
输出:
```json
{
"success": true,
"mobile": "13800138000",
"userId": "user001"
}
```
### 16. 根据 unionid 查询用户 (get-user-by-unionid)
根据 unionid 获取用户 userid。
```bash
npx ts-node scripts/get-user-by-unionid.ts "<unionid>" [--debug]
```
输出:
```json
{
"success": true,
"unionid": "xxxxx",
"userId": "user001"
}
```
### 17. 获取未登录用户列表 (list-inactive-users)
获取指定日期未登录钉钉的员工列表。只能查询一个月内数据每天9点后调用才能确保获取前一天数据。
```bash
npx ts-node scripts/list-inactive-users.ts "<queryDate>" [--deptIds "id1,id2"] [--offset <offset>] [--size <size>] [--debug]
```
输出:
```json
{
"success": true,
"queryDate": "20240115",
"userIds": ["user001", "user002"],
"hasMore": false
}
```
### 18. 查询离职记录列表 (list-resigned-users)
查询指定时间范围内的离职员工记录。仅企业内部应用可用。
```bash
npx ts-node scripts/list-resigned-users.ts "<startTime>" ["<endTime>"] [--nextToken <token>] [--maxResults <max>] [--debug]
```
输出:
```json
{
"success": true,
"startTime": "2024-01-01T00:00:00+08:00",
"endTime": "2024-02-01T00:00:00+08:00",
"records": [
{
"userId": "user001",
"name": "张三",
"leaveTime": "2024-01-15T10:00:00Z",
"leaveReason": "个人原因"
}
]
}
```
### 19. 获取审批实例 ID 列表 (list-approval-instance-ids)
获取指定审批模板在时间段内的审批实例 ID 列表。
```bash
npx ts-node scripts/list-approval-instance-ids.ts <processCode> --startTime <timestamp> --endTime <timestamp> [--size <size>] [--nextToken <token>] [--debug]
```
输出:
```json
{
"success": true,
"processCode": "PROC-XXX",
"instanceIds": ["xxx-123", "xxx-456"],
"totalCount": 2,
"hasMore": false,
"nextToken": null
}
```
### 20. 获取审批实例详情 (get-approval-instance)
获取单个审批实例的详细信息,包括表单数据、审批记录、任务列表等。
```bash
npx ts-node scripts/get-approval-instance.ts <instanceId> [--debug]
```
输出:
```json
{
"success": true,
"instanceId": "xxx-123",
"instance": {
"processInstanceId": "xxx-123",
"title": "请假申请",
"createTimeGMT": "2024-01-01T00:00:00Z",
"finishTimeGMT": "2024-01-01T12:00:00Z",
"originatorUserId": "user001",
"originatorDeptId": "1",
"status": "COMPLETED",
"processCode": "PROC-XXX",
"formComponentValues": [...],
"operationRecords": [...],
"tasks": [...]
}
}
```
### 21. 获取用户发起审批列表 (list-user-initiated-approvals)
获取用户发起的审批实例列表。
```bash
npx ts-node scripts/list-user-initiated-approvals.ts <userId> [--startTime <timestamp>] [--endTime <timestamp>] [--maxResults <max>] [--nextToken <token>] [--debug]
```
输出:
```json
{
"success": true,
"userId": "user001",
"instances": [...],
"totalCount": 5,
"hasMore": false,
"nextToken": null
}
```
### 22. 获取抄送用户审批列表 (list-user-cc-approvals)
获取抄送给用户的审批实例列表。
```bash
npx ts-node scripts/list-user-cc-approvals.ts <userId> [--startTime <timestamp>] [--endTime <timestamp>] [--maxResults <max>] [--nextToken <token>] [--debug]
```
### 23. 获取待处理审批列表 (list-user-todo-approvals)
获取用户待处理的审批任务列表。
```bash
npx ts-node scripts/list-user-todo-approvals.ts <userId> [--maxResults <max>] [--nextToken <token>] [--debug]
```
输出:
```json
{
"success": true,
"userId": "user001",
"instances": [...],
"totalCount": 3,
"hasMore": false,
"nextToken": null
}
```
### 24. 获取已处理审批列表 (list-user-done-approvals)
获取用户已处理的审批实例列表。
```bash
npx ts-node scripts/list-user-done-approvals.ts <userId> [--startTime <timestamp>] [--endTime <timestamp>] [--maxResults <max>] [--nextToken <token>] [--debug]
```
### 25. 获取待审批数量 (get-user-todo-count)
获取用户待审批任务数量。
```bash
npx ts-node scripts/get-user-todo-count.ts <userId> [--debug]
```
输出:
```json
{
"success": true,
"userId": "user001",
"count": 5
}
```
### 26. 发起审批实例 (create-approval-instance)
创建新的审批实例。
```bash
npx ts-node scripts/create-approval-instance.ts <processCode> <originatorUserId> <deptId> '<formValuesJson>' [--ccList "user1,user2"] [--debug]
```
示例:
```bash
npx ts-node scripts/create-approval-instance.ts "PROC-XXX" "user001" "1" '[{"name":"标题","value":"请假申请"},{"name":"请假天数","value":"3"}]'
```
输出:
```json
{
"success": true,
"processCode": "PROC-XXX",
"originatorUserId": "user001",
"instanceId": "xxx-new"
}
```
### 27. 终止审批实例 (terminate-approval-instance)
撤销/终止指定的审批实例。
```bash
npx ts-node scripts/terminate-approval-instance.ts <instanceId> <operatingUserId> [--remark "撤销原因"] [--debug]
```
输出:
```json
{
"success": true,
"instanceId": "xxx-123",
"message": "审批实例已终止"
}
```
### 28. 执行审批任务 (execute-approval-task)
同意或拒绝审批任务。
```bash
npx ts-node scripts/execute-approval-task.ts <instanceId> <userId> <agree|refuse> [--taskId <taskId>] [--remark "审批意见"] [--debug]
```
示例:
```bash
npx ts-node scripts/execute-approval-task.ts "xxx-123" "user001" "agree" --remark "同意申请"
npx ts-node scripts/execute-approval-task.ts "xxx-123" "user001" "refuse" --remark "条件不符"
```
输出:
```json
{
"success": true,
"instanceId": "xxx-123",
"userId": "user001",
"action": "agree",
"message": "已同意审批"
}
```
### 29. 转交审批任务 (transfer-approval-task)
将审批任务转交给其他用户处理。
```bash
npx ts-node scripts/transfer-approval-task.ts <instanceId> <userId> <transferToUserId> [--taskId <taskId>] [--remark "转交原因"] [--debug]
```
输出:
```json
{
"success": true,
"instanceId": "xxx-123",
"userId": "user001",
"transferToUserId": "user002",
"message": "审批任务已转交"
}
```
### 30. 添加审批评论 (add-approval-comment)
为审批实例添加评论。
```bash
npx ts-node scripts/add-approval-comment.ts <instanceId> <userId> "<comment>" [--debug]
```
输出:
```json
{
"success": true,
"instanceId": "xxx-123",
"userId": "user001",
"message": "评论已添加"
}
```
## 错误处理
所有脚本在错误时返回统一格式:
```json
{
"success": false,
"error": {
"code": "ERROR_CODE",
"message": "错误描述"
}
}
```
常见错误码:
- `MISSING_CREDENTIALS` - 未设置环境变量
- `INVALID_ARGUMENTS` - 参数不足
- `AUTH_FAILED` - access_token 获取失败
- `UNKNOWN_ERROR` - API 调用异常

1
.agents/skills/dingtalk-api/node_modules/.bin/acorn generated vendored Symbolic link
View File

@@ -0,0 +1 @@
../acorn/bin/acorn

1
.agents/skills/dingtalk-api/node_modules/.bin/ts-node generated vendored Symbolic link
View File

@@ -0,0 +1 @@
../ts-node/dist/bin.js

View File

@@ -0,0 +1 @@
../ts-node/dist/bin-cwd.js

View File

@@ -0,0 +1 @@
../ts-node/dist/bin-esm.js

View File

@@ -0,0 +1 @@
../ts-node/dist/bin-script.js

View File

@@ -0,0 +1 @@
../ts-node/dist/bin-transpile.js

1
.agents/skills/dingtalk-api/node_modules/.bin/ts-script generated vendored Symbolic link
View File

@@ -0,0 +1 @@
../ts-node/dist/bin-script-deprecated.js

1
.agents/skills/dingtalk-api/node_modules/.bin/tsc generated vendored Symbolic link
View File

@@ -0,0 +1 @@
../typescript/bin/tsc

1
.agents/skills/dingtalk-api/node_modules/.bin/tsserver generated vendored Symbolic link
View File

@@ -0,0 +1 @@
../typescript/bin/tsserver

View File

@@ -0,0 +1,496 @@
{
"name": "dingtalk-api",
"version": "1.4.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"node_modules/@alicloud/credentials": {
"version": "2.4.4",
"resolved": "https://registry.npmjs.org/@alicloud/credentials/-/credentials-2.4.4.tgz",
"integrity": "sha512-/eRAGSKcniLIFQ1UCpDhB/IrHUZisQ1sc65ws/c2avxUMpXwH1rWAohb76SVAUJhiF4mwvLzLJM1Mn1XL4Xe/Q==",
"license": "MIT",
"dependencies": {
"@alicloud/tea-typescript": "^1.8.0",
"httpx": "^2.3.3",
"ini": "^1.3.5",
"kitx": "^2.0.0"
}
},
"node_modules/@alicloud/dingtalk": {
"version": "2.2.38",
"resolved": "https://registry.npmjs.org/@alicloud/dingtalk/-/dingtalk-2.2.38.tgz",
"integrity": "sha512-gcpx7dzruf3/5ecWnVHGtFZgoWcZrHRwPs/TAZVMbk+bTBiSmqXWbv+BcWhhNF9JqRkufybe+QjE4r9B38nSmQ==",
"license": "Apache-2.0",
"dependencies": {
"@alicloud/endpoint-util": "^0.0.2",
"@alicloud/gateway-dingtalk": "^1.0.2",
"@alicloud/gateway-spi": "^0.0.8",
"@alicloud/openapi-client": "^0.4.15",
"@alicloud/openapi-util": "^0.3.2",
"@alicloud/tea-typescript": "^1.7.1",
"@alicloud/tea-util": "^1.4.9"
}
},
"node_modules/@alicloud/endpoint-util": {
"version": "0.0.2",
"resolved": "https://registry.npmjs.org/@alicloud/endpoint-util/-/endpoint-util-0.0.2.tgz",
"integrity": "sha512-7aqVtcRzM0dVUE7bHLP2wKFuZygx5V6MTHBIbhGH3gfkN3/VZ9LlrxhkEfOCYtWfAyo9q0t9ScxQ4khvhweMqw==",
"license": "Apache-2.0"
},
"node_modules/@alicloud/gateway-dingtalk": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/@alicloud/gateway-dingtalk/-/gateway-dingtalk-1.0.2.tgz",
"integrity": "sha512-T8ml6kth/nCRthrtHIYnCYv7+q/41SnJaR8c99491azNSPcmMmgxis5ujYIl5irKm0cvoOCCjI9EWUFb2Tx7JA==",
"license": "ISC",
"dependencies": {
"@alicloud/gateway-spi": "^0.0.8",
"@alicloud/tea-typescript": "^1.7.1",
"@alicloud/tea-util": "^1.4.5"
}
},
"node_modules/@alicloud/gateway-spi": {
"version": "0.0.8",
"resolved": "https://registry.npmjs.org/@alicloud/gateway-spi/-/gateway-spi-0.0.8.tgz",
"integrity": "sha512-KM7fu5asjxZPmrz9sJGHJeSU+cNQNOxW+SFmgmAIrITui5hXL2LB+KNRuzWmlwPjnuA2X3/keq9h6++S9jcV5g==",
"license": "ISC",
"dependencies": {
"@alicloud/credentials": "^2",
"@alicloud/tea-typescript": "^1.7.1"
}
},
"node_modules/@alicloud/openapi-client": {
"version": "0.4.15",
"resolved": "https://registry.npmjs.org/@alicloud/openapi-client/-/openapi-client-0.4.15.tgz",
"integrity": "sha512-4VE0/k5ZdQbAhOSTqniVhuX1k5DUeUMZv74degn3wIWjLY6Bq+hxjaGsaHYlLZ2gA5wUrs8NcI5TE+lIQS3iiA==",
"license": "ISC",
"dependencies": {
"@alicloud/credentials": "^2.4.2",
"@alicloud/gateway-spi": "^0.0.8",
"@alicloud/openapi-util": "^0.3.2",
"@alicloud/tea-typescript": "^1.7.1",
"@alicloud/tea-util": "1.4.9",
"@alicloud/tea-xml": "0.0.3"
}
},
"node_modules/@alicloud/openapi-client/node_modules/@alicloud/tea-util": {
"version": "1.4.9",
"resolved": "https://registry.npmjs.org/@alicloud/tea-util/-/tea-util-1.4.9.tgz",
"integrity": "sha512-S0wz76rGtoPKskQtRTGqeuqBHFj8BqUn0Vh+glXKun2/9UpaaaWmuJwcmtImk6bJZfLYEShDF/kxDmDJoNYiTw==",
"license": "Apache-2.0",
"dependencies": {
"@alicloud/tea-typescript": "^1.5.1",
"kitx": "^2.0.0"
}
},
"node_modules/@alicloud/openapi-util": {
"version": "0.3.3",
"resolved": "https://registry.npmjs.org/@alicloud/openapi-util/-/openapi-util-0.3.3.tgz",
"integrity": "sha512-vf0cQ/q8R2U7ZO88X5hDiu1yV3t/WexRj+YycWxRutkH/xVXfkmpRgps8lmNEk7Ar+0xnY8+daN2T+2OyB9F4A==",
"license": "ISC",
"dependencies": {
"@alicloud/tea-typescript": "^1.7.1",
"@alicloud/tea-util": "^1.3.0",
"kitx": "^2.1.0",
"sm3": "^1.0.3"
}
},
"node_modules/@alicloud/tea-typescript": {
"version": "1.8.0",
"resolved": "https://registry.npmjs.org/@alicloud/tea-typescript/-/tea-typescript-1.8.0.tgz",
"integrity": "sha512-CWXWaquauJf0sW30mgJRVu9aaXyBth5uMBCUc+5vKTK1zlgf3hIqRUjJZbjlwHwQ5y9anwcu18r48nOZb7l2QQ==",
"license": "ISC",
"dependencies": {
"@types/node": "^12.0.2",
"httpx": "^2.2.6"
}
},
"node_modules/@alicloud/tea-typescript/node_modules/@types/node": {
"version": "12.20.55",
"resolved": "https://registry.npmjs.org/@types/node/-/node-12.20.55.tgz",
"integrity": "sha512-J8xLz7q2OFulZ2cyGTLE1TbbZcjpno7FaN6zdJNrgAdrJ+DZzh/uFR6YrTb4C+nXakvud8Q4+rbhoIWlYQbUFQ==",
"license": "MIT"
},
"node_modules/@alicloud/tea-util": {
"version": "1.4.11",
"resolved": "https://registry.npmjs.org/@alicloud/tea-util/-/tea-util-1.4.11.tgz",
"integrity": "sha512-HyPEEQ8F0WoZegiCp7sVdrdm6eBOB+GCvGl4182u69LDFktxfirGLcAx3WExUr1zFWkq2OSmBroTwKQ4w/+Yww==",
"license": "Apache-2.0",
"dependencies": {
"@alicloud/tea-typescript": "^1.5.1",
"@darabonba/typescript": "^1.0.0",
"kitx": "^2.0.0"
}
},
"node_modules/@alicloud/tea-xml": {
"version": "0.0.3",
"resolved": "https://registry.npmjs.org/@alicloud/tea-xml/-/tea-xml-0.0.3.tgz",
"integrity": "sha512-+/9GliugjrLglsXVrd1D80EqqKgGpyA0eQ6+1ZdUOYCaRguaSwz44trX3PaxPu/HhIPJg9PsGQQ3cSLXWZjbAA==",
"license": "Apache-2.0",
"dependencies": {
"@alicloud/tea-typescript": "^1",
"@types/xml2js": "^0.4.5",
"xml2js": "^0.6.0"
}
},
"node_modules/@cspotcode/source-map-support": {
"version": "0.8.1",
"resolved": "https://registry.npmjs.org/@cspotcode/source-map-support/-/source-map-support-0.8.1.tgz",
"integrity": "sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw==",
"dev": true,
"license": "MIT",
"dependencies": {
"@jridgewell/trace-mapping": "0.3.9"
},
"engines": {
"node": ">=12"
}
},
"node_modules/@darabonba/typescript": {
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/@darabonba/typescript/-/typescript-1.0.4.tgz",
"integrity": "sha512-icl8RGTw4DiWRpco6dVh21RS0IqrH4s/eEV36TZvz/e1+paogSZjaAgox7ByrlEuvG+bo5d8miq/dRlqiUaL/w==",
"license": "Apache License 2.0",
"dependencies": {
"@alicloud/tea-typescript": "^1.5.1",
"httpx": "^2.3.2",
"lodash": "^4.17.21",
"moment": "^2.30.1",
"moment-timezone": "^0.5.45",
"xml2js": "^0.6.2"
}
},
"node_modules/@jridgewell/resolve-uri": {
"version": "3.1.2",
"resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz",
"integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=6.0.0"
}
},
"node_modules/@jridgewell/sourcemap-codec": {
"version": "1.5.5",
"resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz",
"integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==",
"dev": true,
"license": "MIT"
},
"node_modules/@jridgewell/trace-mapping": {
"version": "0.3.9",
"resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.9.tgz",
"integrity": "sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"@jridgewell/resolve-uri": "^3.0.3",
"@jridgewell/sourcemap-codec": "^1.4.10"
}
},
"node_modules/@tsconfig/node10": {
"version": "1.0.12",
"resolved": "https://registry.npmjs.org/@tsconfig/node10/-/node10-1.0.12.tgz",
"integrity": "sha512-UCYBaeFvM11aU2y3YPZ//O5Rhj+xKyzy7mvcIoAjASbigy8mHMryP5cK7dgjlz2hWxh1g5pLw084E0a/wlUSFQ==",
"dev": true,
"license": "MIT"
},
"node_modules/@tsconfig/node12": {
"version": "1.0.11",
"resolved": "https://registry.npmjs.org/@tsconfig/node12/-/node12-1.0.11.tgz",
"integrity": "sha512-cqefuRsh12pWyGsIoBKJA9luFu3mRxCA+ORZvA4ktLSzIuCUtWVxGIuXigEwO5/ywWFMZ2QEGKWvkZG1zDMTag==",
"dev": true,
"license": "MIT"
},
"node_modules/@tsconfig/node14": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/@tsconfig/node14/-/node14-1.0.3.tgz",
"integrity": "sha512-ysT8mhdixWK6Hw3i1V2AeRqZ5WfXg1G43mqoYlM2nc6388Fq5jcXyr5mRsqViLx/GJYdoL0bfXD8nmF+Zn/Iow==",
"dev": true,
"license": "MIT"
},
"node_modules/@tsconfig/node16": {
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/@tsconfig/node16/-/node16-1.0.4.tgz",
"integrity": "sha512-vxhUy4J8lyeyinH7Azl1pdd43GJhZH/tP2weN8TntQblOY+A0XbT8DJk1/oCPuOOyg/Ja757rG0CgHcWC8OfMA==",
"dev": true,
"license": "MIT"
},
"node_modules/@types/node": {
"version": "20.19.33",
"resolved": "https://registry.npmjs.org/@types/node/-/node-20.19.33.tgz",
"integrity": "sha512-Rs1bVAIdBs5gbTIKza/tgpMuG1k3U/UMJLWecIMxNdJFDMzcM5LOiLVRYh3PilWEYDIeUDv7bpiHPLPsbydGcw==",
"license": "MIT",
"dependencies": {
"undici-types": "~6.21.0"
}
},
"node_modules/@types/xml2js": {
"version": "0.4.14",
"resolved": "https://registry.npmjs.org/@types/xml2js/-/xml2js-0.4.14.tgz",
"integrity": "sha512-4YnrRemBShWRO2QjvUin8ESA41rH+9nQGLUGZV/1IDhi3SL9OhdpNC/MrulTWuptXKwhx/aDxE7toV0f/ypIXQ==",
"license": "MIT",
"dependencies": {
"@types/node": "*"
}
},
"node_modules/acorn": {
"version": "8.16.0",
"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.16.0.tgz",
"integrity": "sha512-UVJyE9MttOsBQIDKw1skb9nAwQuR5wuGD3+82K6JgJlm/Y+KI92oNsMNGZCYdDsVtRHSak0pcV5Dno5+4jh9sw==",
"dev": true,
"license": "MIT",
"bin": {
"acorn": "bin/acorn"
},
"engines": {
"node": ">=0.4.0"
}
},
"node_modules/acorn-walk": {
"version": "8.3.5",
"resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-8.3.5.tgz",
"integrity": "sha512-HEHNfbars9v4pgpW6SO1KSPkfoS0xVOM/9UzkJltjlsHZmJasxg8aXkuZa7SMf8vKGIBhpUsPluQSqhJFCqebw==",
"dev": true,
"license": "MIT",
"dependencies": {
"acorn": "^8.11.0"
},
"engines": {
"node": ">=0.4.0"
}
},
"node_modules/arg": {
"version": "4.1.3",
"resolved": "https://registry.npmjs.org/arg/-/arg-4.1.3.tgz",
"integrity": "sha512-58S9QDqG0Xx27YwPSt9fJxivjYl432YCwfDMfZ+71RAqUrZef7LrKQZ3LHLOwCS4FLNBplP533Zx895SeOCHvA==",
"dev": true,
"license": "MIT"
},
"node_modules/create-require": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/create-require/-/create-require-1.1.1.tgz",
"integrity": "sha512-dcKFX3jn0MpIaXjisoRvexIJVEKzaq7z2rZKxf+MSr9TkdmHmsU4m2lcLojrj/FHl8mk5VxMmYA+ftRkP/3oKQ==",
"dev": true,
"license": "MIT"
},
"node_modules/debug": {
"version": "4.4.3",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
"integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
"license": "MIT",
"dependencies": {
"ms": "^2.1.3"
},
"engines": {
"node": ">=6.0"
},
"peerDependenciesMeta": {
"supports-color": {
"optional": true
}
}
},
"node_modules/diff": {
"version": "4.0.4",
"resolved": "https://registry.npmjs.org/diff/-/diff-4.0.4.tgz",
"integrity": "sha512-X07nttJQkwkfKfvTPG/KSnE2OMdcUCao6+eXF3wmnIQRn2aPAHH3VxDbDOdegkd6JbPsXqShpvEOHfAT+nCNwQ==",
"dev": true,
"license": "BSD-3-Clause",
"engines": {
"node": ">=0.3.1"
}
},
"node_modules/httpx": {
"version": "2.3.3",
"resolved": "https://registry.npmjs.org/httpx/-/httpx-2.3.3.tgz",
"integrity": "sha512-k1qv94u1b6e+XKCxVbLgYlOypVP9MPGpnN5G/vxFf6tDO4V3xpz3d6FUOY/s8NtPgaq5RBVVgSB+7IHpVxMYzw==",
"license": "MIT",
"dependencies": {
"@types/node": "^20",
"debug": "^4.1.1"
}
},
"node_modules/ini": {
"version": "1.3.8",
"resolved": "https://registry.npmjs.org/ini/-/ini-1.3.8.tgz",
"integrity": "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==",
"license": "ISC"
},
"node_modules/kitx": {
"version": "2.2.0",
"resolved": "https://registry.npmjs.org/kitx/-/kitx-2.2.0.tgz",
"integrity": "sha512-tBMwe6AALTBQJb0woQDD40734NKzb0Kzi3k7wQj9ar3AbP9oqhoVrdXPh7rk2r00/glIgd0YbToIUJsnxWMiIg==",
"license": "MIT",
"dependencies": {
"@types/node": "^22.5.4"
}
},
"node_modules/kitx/node_modules/@types/node": {
"version": "22.19.11",
"resolved": "https://registry.npmjs.org/@types/node/-/node-22.19.11.tgz",
"integrity": "sha512-BH7YwL6rA93ReqeQS1c4bsPpcfOmJasG+Fkr6Y59q83f9M1WcBRHR2vM+P9eOisYRcN3ujQoiZY8uk5W+1WL8w==",
"license": "MIT",
"dependencies": {
"undici-types": "~6.21.0"
}
},
"node_modules/lodash": {
"version": "4.17.23",
"resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.23.tgz",
"integrity": "sha512-LgVTMpQtIopCi79SJeDiP0TfWi5CNEc/L/aRdTh3yIvmZXTnheWpKjSZhnvMl8iXbC1tFg9gdHHDMLoV7CnG+w==",
"license": "MIT"
},
"node_modules/make-error": {
"version": "1.3.6",
"resolved": "https://registry.npmjs.org/make-error/-/make-error-1.3.6.tgz",
"integrity": "sha512-s8UhlNe7vPKomQhC1qFelMokr/Sc3AgNbso3n74mVPA5LTZwkB9NlXf4XPamLxJE8h0gh73rM94xvwRT2CVInw==",
"dev": true,
"license": "ISC"
},
"node_modules/moment": {
"version": "2.30.1",
"resolved": "https://registry.npmjs.org/moment/-/moment-2.30.1.tgz",
"integrity": "sha512-uEmtNhbDOrWPFS+hdjFCBfy9f2YoyzRpwcl+DqpC6taX21FzsTLQVbMV/W7PzNSX6x/bhC1zA3c2UQ5NzH6how==",
"license": "MIT",
"engines": {
"node": "*"
}
},
"node_modules/moment-timezone": {
"version": "0.5.48",
"resolved": "https://registry.npmjs.org/moment-timezone/-/moment-timezone-0.5.48.tgz",
"integrity": "sha512-f22b8LV1gbTO2ms2j2z13MuPogNoh5UzxL3nzNAYKGraILnbGc9NEE6dyiiiLv46DGRb8A4kg8UKWLjPthxBHw==",
"license": "MIT",
"dependencies": {
"moment": "^2.29.4"
},
"engines": {
"node": "*"
}
},
"node_modules/ms": {
"version": "2.1.3",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
"license": "MIT"
},
"node_modules/sax": {
"version": "1.4.4",
"resolved": "https://registry.npmjs.org/sax/-/sax-1.4.4.tgz",
"integrity": "sha512-1n3r/tGXO6b6VXMdFT54SHzT9ytu9yr7TaELowdYpMqY/Ao7EnlQGmAQ1+RatX7Tkkdm6hONI2owqNx2aZj5Sw==",
"license": "BlueOak-1.0.0",
"engines": {
"node": ">=11.0.0"
}
},
"node_modules/sm3": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/sm3/-/sm3-1.0.3.tgz",
"integrity": "sha512-KyFkIfr8QBlFG3uc3NaljaXdYcsbRy1KrSfc4tsQV8jW68jAktGeOcifu530Vx/5LC+PULHT0Rv8LiI8Gw+c1g==",
"license": "MIT"
},
"node_modules/ts-node": {
"version": "10.9.2",
"resolved": "https://registry.npmjs.org/ts-node/-/ts-node-10.9.2.tgz",
"integrity": "sha512-f0FFpIdcHgn8zcPSbf1dRevwt047YMnaiJM3u2w2RewrB+fob/zePZcrOyQoLMMO7aBIddLcQIEK5dYjkLnGrQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"@cspotcode/source-map-support": "^0.8.0",
"@tsconfig/node10": "^1.0.7",
"@tsconfig/node12": "^1.0.7",
"@tsconfig/node14": "^1.0.0",
"@tsconfig/node16": "^1.0.2",
"acorn": "^8.4.1",
"acorn-walk": "^8.1.1",
"arg": "^4.1.0",
"create-require": "^1.1.0",
"diff": "^4.0.1",
"make-error": "^1.1.1",
"v8-compile-cache-lib": "^3.0.1",
"yn": "3.1.1"
},
"bin": {
"ts-node": "dist/bin.js",
"ts-node-cwd": "dist/bin-cwd.js",
"ts-node-esm": "dist/bin-esm.js",
"ts-node-script": "dist/bin-script.js",
"ts-node-transpile-only": "dist/bin-transpile.js",
"ts-script": "dist/bin-script-deprecated.js"
},
"peerDependencies": {
"@swc/core": ">=1.2.50",
"@swc/wasm": ">=1.2.50",
"@types/node": "*",
"typescript": ">=2.7"
},
"peerDependenciesMeta": {
"@swc/core": {
"optional": true
},
"@swc/wasm": {
"optional": true
}
}
},
"node_modules/typescript": {
"version": "5.9.3",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
"integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
"dev": true,
"license": "Apache-2.0",
"bin": {
"tsc": "bin/tsc",
"tsserver": "bin/tsserver"
},
"engines": {
"node": ">=14.17"
}
},
"node_modules/undici-types": {
"version": "6.21.0",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz",
"integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",
"license": "MIT"
},
"node_modules/v8-compile-cache-lib": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/v8-compile-cache-lib/-/v8-compile-cache-lib-3.0.1.tgz",
"integrity": "sha512-wa7YjyUGfNZngI/vtK0UHAN+lgDCxBPCylVXGp0zu59Fz5aiGtNXaq3DhIov063MorB+VfufLh3JlF2KdTK3xg==",
"dev": true,
"license": "MIT"
},
"node_modules/xml2js": {
"version": "0.6.2",
"resolved": "https://registry.npmjs.org/xml2js/-/xml2js-0.6.2.tgz",
"integrity": "sha512-T4rieHaC1EXcES0Kxxj4JWgaUQHDk+qwHcYOCFHfiwKz7tOVPLq7Hjq9dM1WCMhylqMEfP7hMcOIChvotiZegA==",
"license": "MIT",
"dependencies": {
"sax": ">=0.6.0",
"xmlbuilder": "~11.0.0"
},
"engines": {
"node": ">=4.0.0"
}
},
"node_modules/xmlbuilder": {
"version": "11.0.1",
"resolved": "https://registry.npmjs.org/xmlbuilder/-/xmlbuilder-11.0.1.tgz",
"integrity": "sha512-fDlsI/kFEx7gLvbecc0/ohLG50fugQp8ryHzMTuW9vSa1GJ0XYWKnhsUx7oie3G98+r56aTQIUB4kht42R3JvA==",
"license": "MIT",
"engines": {
"node": ">=4.0"
}
},
"node_modules/yn": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/yn/-/yn-3.1.1.tgz",
"integrity": "sha512-Ux4ygGWsu2c7isFWe8Yu1YluJmqVhxqK2cLXNQA5AcC3QfbGNpM7fu0Y8b/z16pXLnFxZYvWhd3fhBY9DLmC6Q==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=6"
}
}
}
}

View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2009-present, Alibaba Cloud All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -0,0 +1,258 @@
English | [简体中文](README-CN.md)
# Alibaba Cloud Credentials for TypeScript/Node.js
[![npm version](https://badge.fury.io/js/@alicloud%2fcredentials.svg)](https://www.npmjs.com/package/@alicloud/credentials)
[![NodeJS](https://github.com/aliyun/credentials-nodejs/actions/workflows/ci.yml/badge.svg)](https://github.com/aliyun/credentials-nodejs/actions/workflows/ci.yml)
[![codecov](https://codecov.io/gh/aliyun/credentials-nodejs/branch/master/graph/badge.svg)](https://codecov.io/gh/aliyun/credentials-nodejs)
[![license](https://img.shields.io/github/license/mashape/apistatus.svg)](LICENSE)
## Installation
```bash
npm install @alicloud/credentials
```
**Node.js >= 12** required.
## Quick Examples
Before you begin, you need to sign up for an Alibaba Cloud account and retrieve your [Credentials](https://usercenter.console.aliyun.com/#/manage/ak).
### Credential Type
#### access_key
Setup access_key credential through [User Information Management][ak], it have full authority over the account, please keep it safe. Sometimes for security reasons, you cannot hand over a primary account AccessKey with full access to the developer of a project. You may create a sub-account [RAM Sub-account][ram] , grant its [authorization][permissions]and use the AccessKey of RAM Sub-account.
```ts
import Credential, { Config } from '@alicloud/credentials';
const config: Config = {
type: 'access_key', // credential type
accessKeyId: 'accessKeyId', // AccessKeyId of your account
accessKeySecret: 'accessKeySecret', // AccessKeySecret of your account
}
const cred = new Credential(config);
const {
accessKeyId,
accessKeySecret,
type
} = await cred.getCredential();
```
#### sts
Create a temporary security credential by applying Temporary Security Credentials (TSC) through the Security Token Service (STS).
```ts
import Credential, { Config } from '@alicloud/credentials';
const config: Config = {
type: 'sts', // credential type
accessKeyId: 'accessKeyId', // AccessKeyId of your account
accessKeySecret: 'accessKeySecret', // AccessKeySecret of your account
securityToken: 'securityToken', // Temporary Security Token
}
const cred = new Credential(config);
const {
accessKeyId,
accessKeySecret,
securityToken,
type
} = await cred.getCredential();
```
#### ram_role_arn
By specifying [RAM Role][RAM Role], the credential will be able to automatically request maintenance of STS Token. If you want to limit the permissions([How to make a policy][policy]) of STS Token, you can assign value for `Policy`.
```ts
import Credential, { Config } from '@alicloud/credentials';
const config: Config = {
type: 'ram_role_arn', // credential type
accessKeyId: 'accessKeyId', // AccessKeyId of your account
accessKeySecret: 'accessKeySecret', // AccessKeySecret of your account
roleArn: 'roleArn', // Format: acs:ram::USER_ID:role/ROLE_NAME
roleSessionName: 'roleSessionName', // Role Session Name
policy: 'policy', // Not required, limit the permissions of STS Token
roleSessionExpiration: 3600, // Not required, limit the Valid time of STS Token
}
const cred = new Credential(config);
const {
accessKeyId,
accessKeySecret,
securityToken,
type
} = await cred.getCredential();
```
#### oidc_role_arn
By specifying [OIDC Role][OIDC Role], the credential will be able to automatically request maintenance of STS Token. If you want to limit the permissions([How to make a policy][policy]) of STS Token, you can assign value for `Policy`.
```ts
import Credential, { Config } from '@alicloud/credentials';
const config: Config = {
type: 'oidc_role_arn', // credential type
roleArn: 'roleArn', // Format: acs:ram::USER_Id:role/ROLE_NAME roleArn can be replaced by setting environment variable: ALIBABA_CLOUD_ROLE_ARN
oidcProviderArn: 'oidcProviderArn', // Format: acs:ram::USER_Id:oidc-provider/ROLE_NAME oidcProviderArn can be replaced by setting environment variable: ALIBABA_CLOUD_OIDC_PROVIDER_ARN
oidcTokenFilePath: '/Users/xxx/xxx', // Format: path OIDCTokenFilePath can be replaced by setting environment variable: ALIBABA_CLOUD_OIDC_TOKEN_FILE
roleSessionName: 'roleSessionName', // Role Session Name
policy: 'policy', // Not required, limit the permissions of STS Token
roleSessionExpiration: 3600, // Not required, limit the Valid time of STS Token
}
const cred = new Credential(config);
const {
accessKeyId,
accessKeySecret,
securityToken,
type
} = await cred.getCredential();
```
#### ecs_ram_role
By specifying the role name, the credential will be able to automatically request maintenance of STS Token.
```ts
import Credential, { Config } from '@alicloud/credentials';
const config: Config = {
type: 'ecs_ram_role', // credential type
roleName: 'roleName', // `roleName` is optional. It will be retrieved automatically if not set. It is highly recommended to set it up to reduce requests.
disableIMDSv1: true, // `disableIMDSv1` is optional and is recommended to be turned on. It can be replaced by setting environment variable: ALIBABA_CLOUD_IMDSV1_DISABLED
}
const cred = new Credential(config);
const {
accessKeyId,
accessKeySecret,
securityToken,
type
} = await cred.getCredential();
```
#### rsa_key_pair
By specifying the public key ID and the private key file, the credential will be able to automatically request maintenance of the AccessKey before sending the request. Only Japan station is supported.
```ts
import Credential, { Config } from '@alicloud/credentials';
const config: Config = {
type: 'rsa_key_pair', // credential type
privateKeyFile: 'privateKeyFile', // The file path to store the PrivateKey
publicKeyId: 'publicKeyId', // PublicKeyId of your account
}
const cred = new Credential(config);
const {
accessKeyId,
accessKeySecret,
securityToken,
type
} = await cred.getCredential();
```
#### credentials_uri
By specifying a local or remote URI to get credentials and refresh automanticly.
```ts
import Credential, { Config } from '@alicloud/credentials';
const config: Config = {
type: 'credentials_uri',
credentialsURI: 'http://a_local_or_remote_address/' //credentialsURI can be replaced by setting environment variable: ALIBABA_CLOUD_CREDENTIALS_URI
};
const cred = new Credential(config);
const {
accessKeyId,
accessKeySecret,
securityToken,
type
} = await cred.getCredential();
```
The URI must reponse meets following conditions:
- response status code is 200
- response body struct must be:
```json
{
"Code": "Success",
"AccessKeySecret": "AccessKeySecret",
"AccessKeyId": "AccessKeyId",
"Expiration": "2021-09-26T03:46:38Z",
"SecurityToken": "SecurityToken"
}
```
#### bearer
If credential is required by the Cloud Call Centre (CCC), please apply for Bearer Token maintenance by yourself.
```ts
import Credential, { Config } from '@alicloud/credentials';
const config: Config = {
type: 'bearer', // credential type
bearerToken: 'bearerToken', // BearerToken of your account
}
const cred = new Credential(config);
let bearerToken: string = await cred.getBearerToken();
let type: string = cred.getType();
```
### Provider
If you call `new Credential()` with empty, it will use provider chain to get credential for you.
#### 1. Environment Credentials
The program first looks for environment credentials in the environment variable. If the `ALIBABA_CLOUD_ACCESS_KEY_ID` and `ALIBABA_CLOUD_ACCESS_KEY_SECRET` environment variables are defined and are not empty, the program will use them to create the default credential. If not, the program loads and looks for the client in the configuration file.
#### 2. Config File
If there is `~/.alibabacloud/credentials` default file (Windows shows `C:\Users\USER_NAME\.alibabacloud\credentials`), the program will automatically create credential with the name of 'default'. The default file may not exist, but a parse error throws an exception. The specified files can also be loaded indefinitely: `AlibabaCloud::load('/data/credentials', 'vfs://AlibabaCloud/credentials', ...);` This configuration file can be shared between different projects and between different tools. Because it is outside the project and will not be accidentally committed to the version control. Environment variables can be used on Windows to refer to the home directory %UserProfile%. Unix-like systems can use the environment variable $HOME or ~ (tilde). The path to the default file can be modified by defining the `ALIBABA_CLOUD_CREDENTIALS_FILE` environment variable.
```ini
[default] # Default credential
type = access_key # Certification type: access_key
access_key_id = foo # access key id
access_key_secret = bar # access key secret
```
#### 3. Instance RAM Role
If the environment variable `ALIBABA_CLOUD_ECS_METADATA` is defined and not empty, the program will take the value of the environment variable as the role name and request `http://100.100.100.200/latest/meta-data/ram/security-credentials/` to get the temporary Security credential.
#### 4. Credentials URI
If the environment variable `ALIBABA_CLOUD_CREDENTIALS_URI` is defined and not empty,
the program will take the value of the environment variable as the credentials uri.
## Test & Coverage
- run test
```sh
npm run test
```
- run code coverage
```sh
npm run cov
```
## License
[MIT](LICENSE)
Copyright (c) 2009-present, Alibaba Cloud All rights reserved.
[ak]: https://usercenter.console.aliyun.com/#/manage/ak
[ram]: https://ram.console.aliyun.com/users
[permissions]: https://ram.console.aliyun.com/permissions
[RAM Role]: https://ram.console.aliyun.com/#/role/list
[OIDC Role]: https://help.aliyun.com/zh/ram/user-guide/role-based-sso-by-using-oidc
[policy]: https://help.aliyun.com/zh/ram/user-guide/policy-management/

View File

@@ -0,0 +1,60 @@
{
"name": "@alicloud/credentials",
"version": "2.4.4",
"description": "alibaba cloud node.js sdk credentials",
"main": "dist/src/client.js",
"scripts": {
"prepublishOnly": "tsc",
"build": "tsc",
"lint": "eslint --fix ./src --ext .ts",
"test": "mocha -b -r ts-node/register test/**/*.test.ts test/*.test.ts --timeout 15000",
"test-dev": "nyc -e .ts -r=html -r=text -r=lcov mocha -b -r ts-node/register",
"cov": "nyc -e .ts -r=html -r=text -r=lcov npm run test",
"ci": "npm run cov",
"integration": "mocha -b -r ts-node/register -R spec integration/*.test.ts",
"clean": "rm -rf coverage"
},
"repository": {
"type": "git",
"url": "git+https://github.com/aliyun/nodejs-credentials.git"
},
"keywords": [
"alibaba cloud",
"sdk",
"credentials"
],
"author": "Alibaba Cloud SDK",
"license": "MIT",
"devDependencies": {
"@types/debug": "^4.1.12",
"@types/expect.js": "^0.3.29",
"@types/ini": "^1.3.30",
"@types/mocha": "^10.0.6",
"@types/node": "^20.11.10",
"@types/rewire": "^2.5.28",
"@typescript-eslint/eslint-plugin": "^6.18.1",
"@typescript-eslint/parser": "^6.18.1",
"eslint": "^8.56.0",
"expect.js": "^0.3.1",
"mm": "^2.4.1",
"mocha": "^10.1.0",
"nyc": "^15.1.0",
"rewire": "^7.0.0",
"ts-node": "^10.9.2",
"typescript": "^4.7.4"
},
"dependencies": {
"@alicloud/tea-typescript": "^1.8.0",
"httpx": "^2.3.3",
"ini": "^1.3.5",
"kitx": "^2.0.0"
},
"bugs": {
"url": "https://github.com/aliyun/nodejs-credentials/issues"
},
"homepage": "https://github.com/aliyun/nodejs-credentials#readme",
"files": [
"src",
"dist"
]
}

View File

@@ -0,0 +1,5 @@
import DefaultCredential from './default_credential';
import ICredential from './icredential';
export default class AccessKeyCredential extends DefaultCredential implements ICredential {
constructor(accessKeyId: string, accessKeySecret: string);
}

View File

@@ -0,0 +1,25 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const default_credential_1 = __importDefault(require("./default_credential"));
const config_1 = __importDefault(require("./config"));
class AccessKeyCredential extends default_credential_1.default {
constructor(accessKeyId, accessKeySecret) {
if (!accessKeyId) {
throw new Error('Missing required accessKeyId option in config for access_key');
}
if (!accessKeySecret) {
throw new Error('Missing required accessKeySecret option in config for access_key');
}
const conf = new config_1.default({
type: 'access_key',
accessKeyId,
accessKeySecret
});
super(conf);
}
}
exports.default = AccessKeyCredential;
//# sourceMappingURL=access_key_credential.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"access_key_credential.js","sourceRoot":"","sources":["../../src/access_key_credential.ts"],"names":[],"mappings":";;;;;AAAA,8EAAqD;AAErD,sDAA8B;AAE9B,MAAqB,mBAAoB,SAAQ,4BAAiB;IAChE,YAAY,WAAmB,EAAE,eAAuB;QACtD,IAAI,CAAC,WAAW,EAAE;YAChB,MAAM,IAAI,KAAK,CAAC,8DAA8D,CAAC,CAAC;SACjF;QAED,IAAI,CAAC,eAAe,EAAE;YACpB,MAAM,IAAI,KAAK,CAAC,kEAAkE,CAAC,CAAC;SACrF;QACD,MAAM,IAAI,GAAG,IAAI,gBAAM,CAAC;YACtB,IAAI,EAAE,YAAY;YAClB,WAAW;YACX,eAAe;SAChB,CAAC,CAAC;QACH,KAAK,CAAC,IAAI,CAAC,CAAC;IACd,CAAC;CACF;AAhBD,sCAgBC"}

View File

@@ -0,0 +1,5 @@
import DefaultCredential from './default_credential';
import ICredential from './icredential';
export default class BearerTokenCredential extends DefaultCredential implements ICredential {
constructor(bearerToken: string);
}

View File

@@ -0,0 +1,21 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const default_credential_1 = __importDefault(require("./default_credential"));
const config_1 = __importDefault(require("./config"));
class BearerTokenCredential extends default_credential_1.default {
constructor(bearerToken) {
if (!bearerToken) {
throw new Error('Missing required bearerToken option in config for bearer');
}
const conf = new config_1.default({
type: 'bearer'
});
super(conf);
this.bearerToken = bearerToken;
}
}
exports.default = BearerTokenCredential;
//# sourceMappingURL=bearer_token_credential.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"bearer_token_credential.js","sourceRoot":"","sources":["../../src/bearer_token_credential.ts"],"names":[],"mappings":";;;;;AAAA,8EAAqD;AAErD,sDAA8B;AAE9B,MAAqB,qBAAsB,SAAQ,4BAAiB;IAElE,YAAY,WAAmB;QAC7B,IAAI,CAAC,WAAW,EAAE;YAChB,MAAM,IAAI,KAAK,CAAC,0DAA0D,CAAC,CAAC;SAC7E;QACD,MAAM,IAAI,GAAG,IAAI,gBAAM,CAAC;YACtB,IAAI,EAAE,QAAQ;SACf,CAAC,CAAC;QACH,KAAK,CAAC,IAAI,CAAC,CAAC;QACZ,IAAI,CAAC,WAAW,GAAG,WAAW,CAAC;IACjC,CAAC;CACF;AAZD,wCAYC"}

View File

@@ -0,0 +1,43 @@
import ICredential from './icredential';
import Config from './config';
import CredentialModel from './credential_model';
import CredentialsProvider from './credentials_provider';
import StaticAKCredentialsProvider from './providers/static_ak';
import StaticSTSCredentialsProvider from './providers/static_sts';
import RAMRoleARNCredentialsProvider from './providers/ram_role_arn';
import OIDCRoleArnCredentialsProvider from './providers/oidc_role_arn';
import ECSRAMRoleCredentialsProvider from './providers/ecs_ram_role';
import DefaultCredentialsProvider from './providers/default';
import URICredentialsProvider from './providers/uri';
import CLIProfileCredentialsProvider from './providers/cli_profile';
import ProfileCredentialsProvider from './providers/profile';
import EnvironmentVariableCredentialsProvider from './providers/env';
export { CredentialModel, Config, DefaultCredentialsProvider, CredentialsProvider, StaticAKCredentialsProvider, StaticSTSCredentialsProvider, RAMRoleARNCredentialsProvider, OIDCRoleArnCredentialsProvider, ECSRAMRoleCredentialsProvider, URICredentialsProvider, EnvironmentVariableCredentialsProvider, ProfileCredentialsProvider, CLIProfileCredentialsProvider };
export default class Credential implements ICredential {
credential: ICredential;
constructor(config?: Config | null, provider?: CredentialsProvider | {
[key: string]: any;
} | null);
/**
* @deprecated Use getCredential() instead of
*/
getAccessKeyId(): Promise<string>;
/**
* @deprecated Use getCredential() instead of
*/
getAccessKeySecret(): Promise<string>;
/**
* @deprecated Use getCredential() instead of
*/
getSecurityToken(): Promise<string>;
/**
* @deprecated Use getCredential() instead of
*/
getBearerToken(): string;
/**
* @deprecated Use getCredential() instead of
*/
getType(): string;
getCredential(): Promise<CredentialModel>;
private load;
}

View File

@@ -0,0 +1,229 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.CLIProfileCredentialsProvider = exports.ProfileCredentialsProvider = exports.EnvironmentVariableCredentialsProvider = exports.URICredentialsProvider = exports.ECSRAMRoleCredentialsProvider = exports.OIDCRoleArnCredentialsProvider = exports.RAMRoleARNCredentialsProvider = exports.StaticSTSCredentialsProvider = exports.StaticAKCredentialsProvider = exports.DefaultCredentialsProvider = exports.Config = exports.CredentialModel = void 0;
const rsa_key_pair_credential_1 = __importDefault(require("./rsa_key_pair_credential"));
const bearer_token_credential_1 = __importDefault(require("./bearer_token_credential"));
const config_1 = __importDefault(require("./config"));
exports.Config = config_1.default;
const credential_model_1 = __importDefault(require("./credential_model"));
exports.CredentialModel = credential_model_1.default;
const static_ak_1 = __importDefault(require("./providers/static_ak"));
exports.StaticAKCredentialsProvider = static_ak_1.default;
const static_sts_1 = __importDefault(require("./providers/static_sts"));
exports.StaticSTSCredentialsProvider = static_sts_1.default;
const ram_role_arn_1 = __importDefault(require("./providers/ram_role_arn"));
exports.RAMRoleARNCredentialsProvider = ram_role_arn_1.default;
const oidc_role_arn_1 = __importDefault(require("./providers/oidc_role_arn"));
exports.OIDCRoleArnCredentialsProvider = oidc_role_arn_1.default;
const ecs_ram_role_1 = __importDefault(require("./providers/ecs_ram_role"));
exports.ECSRAMRoleCredentialsProvider = ecs_ram_role_1.default;
const default_1 = __importDefault(require("./providers/default"));
exports.DefaultCredentialsProvider = default_1.default;
const uri_1 = __importDefault(require("./providers/uri"));
exports.URICredentialsProvider = uri_1.default;
const cli_profile_1 = __importDefault(require("./providers/cli_profile"));
exports.CLIProfileCredentialsProvider = cli_profile_1.default;
const profile_1 = __importDefault(require("./providers/profile"));
exports.ProfileCredentialsProvider = profile_1.default;
const env_1 = __importDefault(require("./providers/env"));
exports.EnvironmentVariableCredentialsProvider = env_1.default;
class InnerCredentialsClient {
constructor(type, provider) {
this.type = type;
this.provider = provider;
}
/**
* @deprecated use getCredential() instead of
* @returns the access key id of credentials
*/
async getAccessKeyId() {
const credentials = await this.provider.getCredentials();
return credentials.accessKeyId;
}
/**
* @deprecated use getCredential() instead of
* @returns the access key secret of credentials
*/
async getAccessKeySecret() {
const credentials = await this.provider.getCredentials();
return credentials.accessKeySecret;
}
/**
* @deprecated use getCredential() instead of
* @returns the security token of credentials
*/
async getSecurityToken() {
const credentials = await this.provider.getCredentials();
return credentials.securityToken;
}
getBearerToken() {
return;
}
getType() {
return this.type;
}
async getCredential() {
const credentials = await this.provider.getCredentials();
return new credential_model_1.default({
accessKeyId: credentials.accessKeyId,
accessKeySecret: credentials.accessKeySecret,
securityToken: credentials.securityToken,
bearerToken: undefined,
type: this.getType(),
providerName: credentials.providerName,
});
}
}
function isCredentialsProviderClass(t) {
if (!t) {
return false;
}
return typeof t.getCredentials === 'function' && typeof t.getProviderName === 'function';
}
class Credential {
constructor(config = null, provider = null) {
if (isCredentialsProviderClass(provider)) {
this.load(null, provider);
}
else {
this.load(config, null);
}
}
/**
* @deprecated Use getCredential() instead of
*/
getAccessKeyId() {
return this.credential.getAccessKeyId();
}
/**
* @deprecated Use getCredential() instead of
*/
getAccessKeySecret() {
return this.credential.getAccessKeySecret();
}
/**
* @deprecated Use getCredential() instead of
*/
getSecurityToken() {
return this.credential.getSecurityToken();
}
/**
* @deprecated Use getCredential() instead of
*/
getBearerToken() {
return this.credential.getBearerToken();
}
/**
* @deprecated Use getCredential() instead of
*/
getType() {
return this.credential.getType();
}
getCredential() {
return this.credential.getCredential();
}
load(config, provider) {
if (provider) {
this.credential = new InnerCredentialsClient(provider.getProviderName(), provider);
return;
}
if (!config) {
this.credential = new InnerCredentialsClient('default', default_1.default.builder().build());
return;
}
if (!config.type) {
throw new Error('Missing required type option');
}
switch (config.type) {
case 'access_key':
this.credential = new InnerCredentialsClient('access_key', static_ak_1.default.builder()
.withAccessKeyId(config.accessKeyId)
.withAccessKeySecret(config.accessKeySecret)
.build());
break;
case 'sts':
this.credential = new InnerCredentialsClient('sts', static_sts_1.default.builder()
.withAccessKeyId(config.accessKeyId)
.withAccessKeySecret(config.accessKeySecret)
.withSecurityToken(config.securityToken)
.build());
break;
case 'ecs_ram_role':
this.credential = new InnerCredentialsClient('ecs_ram_role', ecs_ram_role_1.default.builder()
.withRoleName(config.roleName)
.withDisableIMDSv1(config.disableIMDSv1)
.withAsyncCredentialUpdateEnabled(config.asyncCredentialUpdateEnabled)
.withReadTimeout(config.timeout)
.withConnectTimeout(config.connectTimeout)
.build());
break;
case 'ram_role_arn':
{
let credentialsProvider;
if (config.securityToken) {
credentialsProvider = static_sts_1.default.builder()
.withAccessKeyId(config.accessKeyId)
.withAccessKeySecret(config.accessKeySecret)
.withSecurityToken(config.securityToken)
.build();
}
else {
credentialsProvider = static_ak_1.default.builder()
.withAccessKeyId(config.accessKeyId)
.withAccessKeySecret(config.accessKeySecret)
.build();
}
this.credential = new InnerCredentialsClient('ram_role_arn', ram_role_arn_1.default.builder()
.withCredentialsProvider(credentialsProvider)
.withRoleArn(config.roleArn)
.withPolicy(config.policy)
.withDurationSeconds(config.roleSessionExpiration)
.withRoleSessionName(config.roleSessionName)
.withReadTimeout(config.timeout)
.withConnectTimeout(config.connectTimeout)
.withEnableVpc(config.enableVpc)
.withStsEndpoint(config.stsEndpoint)
.withStsRegionId(config.stsRegionId)
.withExternalId(config.externalId)
// .withHttpOptions(runtime)
.build());
}
break;
case 'oidc_role_arn':
this.credential = new InnerCredentialsClient('oidc_role_arn', oidc_role_arn_1.default.builder()
.withRoleArn(config.roleArn)
.withOIDCProviderArn(config.oidcProviderArn)
.withOIDCTokenFilePath(config.oidcTokenFilePath)
.withRoleSessionName(config.roleSessionName)
.withPolicy(config.policy)
.withDurationSeconds(config.roleSessionExpiration)
.withStsEndpoint(config.stsEndpoint)
.withStsRegionId(config.stsRegionId)
.withEnableVpc(config.enableVpc)
.withReadTimeout(config.timeout)
.withConnectTimeout(config.connectTimeout)
.build());
break;
case 'rsa_key_pair':
this.credential = new rsa_key_pair_credential_1.default(config.publicKeyId, config.privateKeyFile);
break;
case 'bearer':
this.credential = new bearer_token_credential_1.default(config.bearerToken);
break;
case 'credentials_uri':
this.credential = new InnerCredentialsClient('credentials_uri', uri_1.default.builder()
.withCredentialsURI(config.credentialsURI)
.withReadTimeout(config.timeout)
.withConnectTimeout(config.connectTimeout)
.build());
break;
default:
throw new Error('Invalid type option, support: access_key, sts, ecs_ram_role, ram_role_arn, rsa_key_pair, credentials_uri');
}
}
}
exports.default = Credential;
//# sourceMappingURL=client.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,36 @@
import * as $tea from '@alicloud/tea-typescript';
export default class Config extends $tea.Model {
accessKeyId?: string;
accessKeySecret?: string;
securityToken?: string;
bearerToken?: string;
durationSeconds?: number;
roleArn?: string;
policy?: string;
roleSessionExpiration?: number;
roleSessionName?: string;
publicKeyId?: string;
privateKeyFile?: string;
roleName?: string;
enableIMDSv2?: boolean;
disableIMDSv1: boolean;
asyncCredentialUpdateEnabled: boolean;
metadataTokenDuration?: number;
credentialsURI?: string;
oidcProviderArn: string;
oidcTokenFilePath: string;
type?: string;
externalId?: string;
stsEndpoint?: string;
timeout?: number;
connectTimeout?: number;
static names(): {
[key: string]: string;
};
static types(): {
[key: string]: any;
};
constructor(config?: {
[key: string]: any;
});
}

View File

@@ -0,0 +1,93 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const $tea = __importStar(require("@alicloud/tea-typescript"));
class Config extends $tea.Model {
static names() {
return {
accessKeyId: 'accessKeyId',
accessKeySecret: 'accessKeySecret',
securityToken: 'securityToken',
bearerToken: 'bearerToken',
durationSeconds: 'durationSeconds',
roleArn: 'roleArn',
policy: 'policy',
roleSessionExpiration: 'roleSessionExpiration',
roleSessionName: 'roleSessionName',
externalId: 'externalId',
stsEndpoint: 'stsEndpoint',
stsRegionId: 'stsRegionId',
enableVpc: 'enableVpc',
timeout: 'readTimeout',
connectTimeout: 'connectTimeout',
publicKeyId: 'publicKeyId',
privateKeyFile: 'privateKeyFile',
roleName: 'roleName',
enableIMDSv2: 'enableIMDSv2',
disableIMDSv1: 'disableIMDSv1',
asyncCredentialUpdateEnabled: 'asyncCredentialUpdateEnabled',
metadataTokenDuration: 'metadataTokenDuration',
credentialsURI: 'credentialsURI',
oidcProviderArn: 'oidcProviderArn',
oidcTokenFilePath: 'oidcTokenFilePath',
type: 'type',
};
}
static types() {
return {
accessKeyId: 'string',
accessKeySecret: 'string',
securityToken: 'string',
bearerToken: 'string',
durationSeconds: 'number',
roleArn: 'string',
policy: 'string',
roleSessionExpiration: 'number',
roleSessionName: 'string',
externalId: 'string',
stsEndpoint: 'string',
stsRegionId: 'string',
enableVpc: 'string',
timeout: 'number',
connectTimeout: 'number',
publicKeyId: 'string',
privateKeyFile: 'string',
roleName: 'string',
enableIMDSv2: 'boolean',
disableIMDSv1: 'boolean',
asyncCredentialUpdateEnabled: 'boolean',
metadataTokenDuration: 'number',
credentialsURI: 'string',
oidcProviderArn: 'string',
oidcTokenFilePath: 'string',
type: 'string',
};
}
constructor(config) {
super(config);
}
}
exports.default = Config;
//# sourceMappingURL=config.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"config.js","sourceRoot":"","sources":["../../src/config.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAAA,+DAAiD;AAEjD,MAAqB,MAAO,SAAQ,IAAI,CAAC,KAAK;IA0B5C,MAAM,CAAC,KAAK;QACV,OAAO;YACL,WAAW,EAAE,aAAa;YAC1B,eAAe,EAAE,iBAAiB;YAClC,aAAa,EAAE,eAAe;YAC9B,WAAW,EAAE,aAAa;YAC1B,eAAe,EAAE,iBAAiB;YAClC,OAAO,EAAE,SAAS;YAClB,MAAM,EAAE,QAAQ;YAChB,qBAAqB,EAAE,uBAAuB;YAC9C,eAAe,EAAE,iBAAiB;YAClC,UAAU,EAAE,YAAY;YACxB,WAAW,EAAE,aAAa;YAC1B,WAAW,EAAE,aAAa;YAC1B,SAAS,EAAE,WAAW;YACtB,OAAO,EAAE,aAAa;YACtB,cAAc,EAAE,gBAAgB;YAChC,WAAW,EAAE,aAAa;YAC1B,cAAc,EAAE,gBAAgB;YAChC,QAAQ,EAAE,UAAU;YACpB,YAAY,EAAE,cAAc;YAC5B,aAAa,EAAE,eAAe;YAC9B,4BAA4B,EAAE,8BAA8B;YAC5D,qBAAqB,EAAE,uBAAuB;YAC9C,cAAc,EAAE,gBAAgB;YAChC,eAAe,EAAE,iBAAiB;YAClC,iBAAiB,EAAE,mBAAmB;YACtC,IAAI,EAAE,MAAM;SACb,CAAC;IACJ,CAAC;IAED,MAAM,CAAC,KAAK;QACV,OAAO;YACL,WAAW,EAAE,QAAQ;YACrB,eAAe,EAAE,QAAQ;YACzB,aAAa,EAAE,QAAQ;YACvB,WAAW,EAAE,QAAQ;YACrB,eAAe,EAAE,QAAQ;YACzB,OAAO,EAAE,QAAQ;YACjB,MAAM,EAAE,QAAQ;YAChB,qBAAqB,EAAE,QAAQ;YAC/B,eAAe,EAAE,QAAQ;YACzB,UAAU,EAAE,QAAQ;YACpB,WAAW,EAAE,QAAQ;YACrB,WAAW,EAAE,QAAQ;YACrB,SAAS,EAAE,QAAQ;YACnB,OAAO,EAAE,QAAQ;YACjB,cAAc,EAAE,QAAQ;YACxB,WAAW,EAAE,QAAQ;YACrB,cAAc,EAAE,QAAQ;YACxB,QAAQ,EAAE,QAAQ;YAClB,YAAY,EAAE,SAAS;YACvB,aAAa,EAAE,SAAS;YACxB,4BAA4B,EAAE,SAAS;YACvC,qBAAqB,EAAE,QAAQ;YAC/B,cAAc,EAAE,QAAQ;YACxB,eAAe,EAAE,QAAQ;YACzB,iBAAiB,EAAE,QAAQ;YAC3B,IAAI,EAAE,QAAQ;SACf,CAAC;IACJ,CAAC;IAED,YAAY,MAA+B;QACzC,KAAK,CAAC,MAAM,CAAC,CAAC;IAChB,CAAC;CACF;AA3FD,yBA2FC"}

View File

@@ -0,0 +1,18 @@
import * as $tea from '@alicloud/tea-typescript';
export default class CredentialModel extends $tea.Model {
accessKeyId?: string;
accessKeySecret?: string;
securityToken?: string;
bearerToken?: string;
type?: string;
providerName?: string;
static names(): {
[key: string]: string;
};
static types(): {
[key: string]: any;
};
constructor(map?: {
[key: string]: any;
});
}

View File

@@ -0,0 +1,53 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const $tea = __importStar(require("@alicloud/tea-typescript"));
class CredentialModel extends $tea.Model {
static names() {
return {
accessKeyId: 'accessKeyId',
accessKeySecret: 'accessKeySecret',
securityToken: 'securityToken',
bearerToken: 'bearerToken',
type: 'type',
providerName: 'providerName',
};
}
static types() {
return {
accessKeyId: 'string',
accessKeySecret: 'string',
securityToken: 'string',
bearerToken: 'string',
type: 'string',
providerName: 'string',
};
}
constructor(map) {
super(map);
}
}
exports.default = CredentialModel;
//# sourceMappingURL=credential_model.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"credential_model.js","sourceRoot":"","sources":["../../src/credential_model.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAAA,+DAAiD;AAEjD,MAAqB,eAAgB,SAAQ,IAAI,CAAC,KAAK;IAOrD,MAAM,CAAC,KAAK;QACV,OAAO;YACL,WAAW,EAAE,aAAa;YAC1B,eAAe,EAAE,iBAAiB;YAClC,aAAa,EAAE,eAAe;YAC9B,WAAW,EAAE,aAAa;YAC1B,IAAI,EAAE,MAAM;YACZ,YAAY,EAAE,cAAc;SAC7B,CAAC;IACJ,CAAC;IAED,MAAM,CAAC,KAAK;QACV,OAAO;YACL,WAAW,EAAE,QAAQ;YACrB,eAAe,EAAE,QAAQ;YACzB,aAAa,EAAE,QAAQ;YACvB,WAAW,EAAE,QAAQ;YACrB,IAAI,EAAE,QAAQ;YACd,YAAY,EAAE,QAAQ;SACvB,CAAC;IACJ,CAAC;IAED,YAAY,GAA4B;QACtC,KAAK,CAAC,GAAG,CAAC,CAAC;IACb,CAAC;CACF;AAhCD,kCAgCC"}

View File

@@ -0,0 +1,19 @@
export default class Credentials {
readonly accessKeyId: string;
readonly accessKeySecret: string;
readonly securityToken: string;
readonly providerName: string;
constructor(builder: CredentialsBuilder);
static builder(): CredentialsBuilder;
}
export declare class CredentialsBuilder {
accessKeyId: string;
accessKeySecret: string;
securityToken: string;
providerName: string;
withAccessKeyId(value: string): this;
withAccessKeySecret(value: string): this;
withSecurityToken(value: string): this;
withProviderName(value: string): this;
build(): Credentials;
}

View File

@@ -0,0 +1,38 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CredentialsBuilder = void 0;
class Credentials {
constructor(builder) {
this.accessKeyId = builder.accessKeyId;
this.accessKeySecret = builder.accessKeySecret;
this.securityToken = builder.securityToken;
this.providerName = builder.providerName;
}
static builder() {
return new CredentialsBuilder();
}
}
exports.default = Credentials;
class CredentialsBuilder {
withAccessKeyId(value) {
this.accessKeyId = value;
return this;
}
withAccessKeySecret(value) {
this.accessKeySecret = value;
return this;
}
withSecurityToken(value) {
this.securityToken = value;
return this;
}
withProviderName(value) {
this.providerName = value;
return this;
}
build() {
return new Credentials(this);
}
}
exports.CredentialsBuilder = CredentialsBuilder;
//# sourceMappingURL=credentials.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"credentials.js","sourceRoot":"","sources":["../../src/credentials.ts"],"names":[],"mappings":";;;AAAA,MAAqB,WAAW;IAM9B,YAAY,OAA4B;QACtC,IAAI,CAAC,WAAW,GAAG,OAAO,CAAC,WAAW,CAAC;QACvC,IAAI,CAAC,eAAe,GAAG,OAAO,CAAC,eAAe,CAAC;QAC/C,IAAI,CAAC,aAAa,GAAG,OAAO,CAAC,aAAa,CAAC;QAC3C,IAAI,CAAC,YAAY,GAAG,OAAO,CAAC,YAAY,CAAC;IAC3C,CAAC;IAED,MAAM,CAAC,OAAO;QACZ,OAAO,IAAI,kBAAkB,EAAE,CAAC;IAClC,CAAC;CACF;AAhBD,8BAgBC;AAED,MAAa,kBAAkB;IAMtB,eAAe,CAAC,KAAa;QAClC,IAAI,CAAC,WAAW,GAAG,KAAK,CAAC;QACzB,OAAO,IAAI,CAAC;IACd,CAAC;IAEM,mBAAmB,CAAC,KAAa;QACtC,IAAI,CAAC,eAAe,GAAG,KAAK,CAAC;QAC7B,OAAO,IAAI,CAAC;IACd,CAAC;IAEM,iBAAiB,CAAC,KAAa;QACpC,IAAI,CAAC,aAAa,GAAG,KAAK,CAAC;QAC3B,OAAO,IAAI,CAAC;IACd,CAAC;IAEM,gBAAgB,CAAC,KAAa;QACnC,IAAI,CAAC,YAAY,GAAG,KAAK,CAAC;QAC1B,OAAO,IAAI,CAAC;IACd,CAAC;IAEM,KAAK;QACV,OAAO,IAAI,WAAW,CAAC,IAAI,CAAC,CAAC;IAC/B,CAAC;CACF;AA7BD,gDA6BC"}

View File

@@ -0,0 +1,5 @@
import Credentials from './credentials';
export default interface CredentialsProvider {
getCredentials: () => Promise<Credentials>;
getProviderName: () => string;
}

View File

@@ -0,0 +1,3 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=credentials_provider.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"credentials_provider.js","sourceRoot":"","sources":["../../src/credentials_provider.ts"],"names":[],"mappings":""}

View File

@@ -0,0 +1,17 @@
import Config from './config';
import CredentialModel from './credential_model';
import ICredential from './icredential';
export default class DefaultCredential implements ICredential {
accessKeyId: string;
accessKeySecret: string;
securityToken?: string;
bearerToken?: string;
type: string;
constructor(config: Config);
getAccessKeyId(): Promise<string>;
getAccessKeySecret(): Promise<string>;
getSecurityToken(): Promise<string>;
getBearerToken(): string;
getType(): string;
getCredential(): Promise<CredentialModel>;
}

View File

@@ -0,0 +1,41 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const credential_model_1 = __importDefault(require("./credential_model"));
class DefaultCredential {
constructor(config) {
this.accessKeyId = config.accessKeyId || '';
this.accessKeySecret = config.accessKeySecret || '';
this.securityToken = config.securityToken || '';
this.bearerToken = config.bearerToken || '';
this.type = config.type || '';
}
async getAccessKeyId() {
return this.accessKeyId;
}
async getAccessKeySecret() {
return this.accessKeySecret;
}
async getSecurityToken() {
return this.securityToken;
}
getBearerToken() {
return this.bearerToken;
}
getType() {
return this.type;
}
async getCredential() {
return new credential_model_1.default({
accessKeyId: this.accessKeyId,
accessKeySecret: this.accessKeySecret,
securityToken: this.securityToken,
bearerToken: this.bearerToken,
type: this.type,
});
}
}
exports.default = DefaultCredential;
//# sourceMappingURL=default_credential.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"default_credential.js","sourceRoot":"","sources":["../../src/default_credential.ts"],"names":[],"mappings":";;;;;AACA,0EAAiD;AAGjD,MAAqB,iBAAiB;IAOpC,YAAY,MAAc;QACxB,IAAI,CAAC,WAAW,GAAG,MAAM,CAAC,WAAW,IAAI,EAAE,CAAC;QAC5C,IAAI,CAAC,eAAe,GAAG,MAAM,CAAC,eAAe,IAAI,EAAE,CAAC;QACpD,IAAI,CAAC,aAAa,GAAG,MAAM,CAAC,aAAa,IAAI,EAAE,CAAC;QAChD,IAAI,CAAC,WAAW,GAAG,MAAM,CAAC,WAAW,IAAI,EAAE,CAAC;QAC5C,IAAI,CAAC,IAAI,GAAG,MAAM,CAAC,IAAI,IAAI,EAAE,CAAC;IAChC,CAAC;IAED,KAAK,CAAC,cAAc;QAClB,OAAO,IAAI,CAAC,WAAW,CAAC;IAC1B,CAAC;IAED,KAAK,CAAC,kBAAkB;QACtB,OAAO,IAAI,CAAC,eAAe,CAAC;IAC9B,CAAC;IAED,KAAK,CAAC,gBAAgB;QACpB,OAAO,IAAI,CAAC,aAAa,CAAC;IAC5B,CAAC;IAED,cAAc;QACZ,OAAO,IAAI,CAAC,WAAW,CAAC;IAC1B,CAAC;IAED,OAAO;QACL,OAAO,IAAI,CAAC,IAAI,CAAC;IACnB,CAAC;IAED,KAAK,CAAC,aAAa;QACjB,OAAO,IAAI,0BAAe,CAAC;YACzB,WAAW,EAAE,IAAI,CAAC,WAAW;YAC7B,eAAe,EAAE,IAAI,CAAC,eAAe;YACrC,aAAa,EAAE,IAAI,CAAC,aAAa;YACjC,WAAW,EAAE,IAAI,CAAC,WAAW;YAC7B,IAAI,EAAE,IAAI,CAAC,IAAI;SAChB,CAAC,CAAC;IACL,CAAC;CACF;AA5CD,oCA4CC"}

View File

@@ -0,0 +1,24 @@
import SessionCredential from './session_credential';
import ICredential from './icredential';
export default class EcsRamRoleCredential extends SessionCredential implements ICredential {
roleName: string;
enableIMDSv2: boolean;
metadataTokenDuration?: number;
runtime: {
[key: string]: any;
};
metadataToken?: string;
staleTime?: number;
readTimeout?: number;
connectTimeout?: number;
constructor(roleName?: string, runtime?: {
[key: string]: any;
}, enableIMDSv2?: boolean, metadataTokenDuration?: number);
getBody(url: string, options?: {
[key: string]: any;
}): Promise<string>;
getMetadataToken(): Promise<string>;
updateCredential(): Promise<void>;
getRoleName(): Promise<string>;
needToRefresh(): boolean;
}

View File

@@ -0,0 +1,80 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const session_credential_1 = __importDefault(require("./session_credential"));
const httpx_1 = __importDefault(require("httpx"));
const config_1 = __importDefault(require("./config"));
const SECURITY_CRED_URL = 'http://100.100.100.200/latest/meta-data/ram/security-credentials/';
const SECURITY_CRED_TOKEN_URL = 'http://100.100.100.200/latest/api/token';
class EcsRamRoleCredential extends session_credential_1.default {
constructor(roleName = '', runtime = {}, enableIMDSv2 = false, metadataTokenDuration = 21600) {
const conf = new config_1.default({
type: 'ecs_ram_role',
});
super(conf);
this.roleName = roleName;
this.enableIMDSv2 = enableIMDSv2;
this.metadataTokenDuration = metadataTokenDuration;
this.runtime = runtime;
this.sessionCredential = null;
this.metadataToken = null;
this.staleTime = 0;
}
async getBody(url, options = {}) {
const response = await httpx_1.default.request(url, options);
return (await httpx_1.default.read(response, 'utf8'));
}
async getMetadataToken() {
if (this.needToRefresh()) {
let tmpTime = new Date().getTime() + this.metadataTokenDuration * 1000;
const response = await httpx_1.default.request(SECURITY_CRED_TOKEN_URL, {
headers: {
'X-aliyun-ecs-metadata-token-ttl-seconds': `${this.metadataTokenDuration}`
},
method: "PUT"
});
if (response.statusCode !== 200) {
throw new Error(`Failed to get token from ECS Metadata Service. HttpCode=${response.statusCode}`);
}
this.staleTime = tmpTime;
return (await httpx_1.default.read(response, 'utf8'));
}
return this.metadataToken;
}
async updateCredential() {
let options = {};
if (this.enableIMDSv2) {
this.metadataToken = await this.getMetadataToken();
options = {
headers: {
'X-aliyun-ecs-metadata-token': this.metadataToken
},
readTimeout: this.readTimeout,
connectTimeout: this.connectTimeout
};
}
const roleName = await this.getRoleName();
const url = SECURITY_CRED_URL + roleName;
const body = await this.getBody(url, options);
const json = JSON.parse(body);
this.sessionCredential = {
AccessKeyId: json.AccessKeyId,
AccessKeySecret: json.AccessKeySecret,
Expiration: json.Expiration,
SecurityToken: json.SecurityToken,
};
}
async getRoleName() {
if (this.roleName && this.roleName.length) {
return this.roleName;
}
return await this.getBody(SECURITY_CRED_URL);
}
needToRefresh() {
return new Date().getTime() >= this.staleTime;
}
}
exports.default = EcsRamRoleCredential;
//# sourceMappingURL=ecs_ram_role_credential.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"ecs_ram_role_credential.js","sourceRoot":"","sources":["../../src/ecs_ram_role_credential.ts"],"names":[],"mappings":";;;;;AAAA,8EAAqD;AACrD,kDAA0B;AAE1B,sDAA8B;AAE9B,MAAM,iBAAiB,GAAG,mEAAmE,CAAC;AAC9F,MAAM,uBAAuB,GAAG,yCAAyC,CAAC;AAE1E,MAAqB,oBAAqB,SAAQ,4BAAiB;IAUjE,YAAY,WAAmB,EAAE,EAAE,UAAkC,EAAE,EAAE,eAAwB,KAAK,EAAE,wBAAgC,KAAK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AC;IAChD,CAAC;CACF;AAlFD,uCAkFC"}

View File

@@ -0,0 +1,9 @@
import CredentialModel from './credential_model';
export default interface ICredential {
getAccessKeyId: () => Promise<string>;
getAccessKeySecret: () => Promise<string>;
getSecurityToken: () => Promise<string>;
getBearerToken: () => string;
getType: () => string;
getCredential: () => Promise<CredentialModel>;
}

View File

@@ -0,0 +1,3 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=icredential.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"icredential.js","sourceRoot":"","sources":["../../src/icredential.ts"],"names":[],"mappings":""}

View File

@@ -0,0 +1,19 @@
import SessionCredential from './session_credential';
import Config from './config';
export default class OidcRoleArnCredential extends SessionCredential {
roleArn: string;
oidcProviderArn: string;
oidcTokenFilePath: string;
policy: string;
durationSeconds: number;
roleSessionName: string;
runtime: {
[key: string]: any;
};
host: string;
constructor(config: Config, runtime?: {
[key: string]: any;
});
private getOdicToken;
updateCredential(): Promise<void>;
}

View File

@@ -0,0 +1,79 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const session_credential_1 = __importDefault(require("./session_credential"));
const http_1 = require("./util/http");
const config_1 = __importDefault(require("./config"));
const fs_1 = __importDefault(require("fs"));
class OidcRoleArnCredential extends session_credential_1.default {
constructor(config, runtime = {}) {
if (!config.roleArn) {
config.roleArn = process.env.ALIBABA_CLOUD_ROLE_ARN;
if (!config.roleArn) {
throw new Error('roleArn does not exist and env ALIBABA_CLOUD_ROLE_ARN is null.');
}
}
if (!config.oidcProviderArn) {
config.oidcProviderArn = process.env.ALIBABA_CLOUD_OIDC_PROVIDER_ARN;
if (!config.oidcProviderArn) {
throw new Error('oidcProviderArn does not exist and env ALIBABA_CLOUD_OIDC_PROVIDER_ARN is null.');
}
}
if (!config.oidcTokenFilePath) {
config.oidcTokenFilePath = process.env.ALIBABA_CLOUD_OIDC_TOKEN_FILE;
if (!config.oidcTokenFilePath) {
throw new Error('oidcTokenFilePath is not exists and env ALIBABA_CLOUD_OIDC_TOKEN_FILE is null.');
}
}
if (!config.roleSessionName && process.env.ALIBABA_CLOUD_ROLE_SESSION_NAME) {
config.roleSessionName = process.env.ALIBABA_CLOUD_ROLE_SESSION_NAME;
}
const conf = new config_1.default({
type: 'oidc_role_arn'
});
super(conf);
this.oidcTokenFilePath = config.oidcTokenFilePath;
this.roleArn = config.roleArn;
this.policy = config.policy;
this.oidcProviderArn = config.oidcProviderArn;
this.durationSeconds = config.roleSessionExpiration || 3600;
this.roleSessionName = config.roleSessionName || 'role_session_name';
runtime.method = 'POST';
runtime.anonymous = true;
this.runtime = runtime;
this.host = 'https://sts.aliyuncs.com';
}
getOdicToken(oidcTokenFilePath) {
if (!fs_1.default.existsSync(oidcTokenFilePath)) {
throw new Error(`oidcTokenFilePath ${oidcTokenFilePath} is not exists.`);
}
let oidcToken = null;
try {
oidcToken = fs_1.default.readFileSync(oidcTokenFilePath, 'utf-8');
}
catch (err) {
throw new Error(`oidcTokenFilePath ${oidcTokenFilePath} cannot be read.`);
}
return oidcToken;
}
async updateCredential() {
const oidcToken = this.getOdicToken(this.oidcTokenFilePath);
const params = {
Action: 'AssumeRoleWithOIDC',
RoleArn: this.roleArn,
OIDCProviderArn: this.oidcProviderArn,
OIDCToken: oidcToken,
DurationSeconds: this.durationSeconds,
RoleSessionName: this.roleSessionName
};
if (this.policy) {
params.policy = this.policy;
}
const json = await (0, http_1.request)(this.host, params, this.runtime);
this.sessionCredential = json.Credentials;
}
}
exports.default = OidcRoleArnCredential;
//# sourceMappingURL=oidc_role_arn_credential.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"oidc_role_arn_credential.js","sourceRoot":"","sources":["../../src/oidc_role_arn_credential.ts"],"names":[],"mappings":";;;;;AAAA,8EAAqD;AACrD,sCAAsC;AACtC,sDAA8B;AAC9B,4CAAoB;AAEpB,MAAqB,qBAAsB,SAA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,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC;QAC5D,IAAI,CAAC,iBAAiB,GAAG,IAAI,CAAC,WAAW,CAAC;IAC5C,CAAC;CACF;AAjFD,wCAiFC"}

View File

@@ -0,0 +1,5 @@
import ICredential from '../icredential';
declare const _default: {
getCredential(): ICredential;
};
export default _default;

View File

@@ -0,0 +1,16 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const uri_credential_1 = __importDefault(require("../uri_credential"));
exports.default = {
getCredential() {
const credentialsURI = process.env.ALIBABA_CLOUD_CREDENTIALS_URI;
if (credentialsURI) {
return new uri_credential_1.default(credentialsURI);
}
return null;
}
};
//# sourceMappingURL=credentials_uri_provider.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"credentials_uri_provider.js","sourceRoot":"","sources":["../../../src/provider/credentials_uri_provider.ts"],"names":[],"mappings":";;;;;AAAA,uEAA8C;AAG9C,kBAAe;IACb,aAAa;QACX,MAAM,cAAc,GAAG,OAAO,CAAC,GAAG,CAAC,6BAA6B,CAAC;QACjE,IAAI,cAAc,EAAE;YAClB,OAAO,IAAI,wBAAa,CAAC,cAAc,CAAC,CAAC;SAC1C;QAED,OAAO,IAAI,CAAC;IACd,CAAC;CACF,CAAA"}

View File

@@ -0,0 +1,5 @@
import ICredential from '../icredential';
declare const _default: {
getCredential(): ICredential;
};
export default _default;

View File

@@ -0,0 +1,23 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const access_key_credential_1 = __importDefault(require("../access_key_credential"));
exports.default = {
getCredential() {
const accessKeyId = process.env.ALIBABA_CLOUD_ACCESS_KEY_ID;
const accessKeySecret = process.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET;
if (accessKeyId === undefined || accessKeySecret === undefined) {
return null;
}
if (accessKeyId === null || accessKeyId === '') {
throw new Error('Environment variable ALIBABA_CLOUD_ACCESS_KEY_ID cannot be empty');
}
if (accessKeySecret === null || accessKeySecret === '') {
throw new Error('Environment variable ALIBABA_CLOUD_ACCESS_KEY_SECRET cannot be empty');
}
return new access_key_credential_1.default(accessKeyId, accessKeySecret);
}
};
//# sourceMappingURL=environment_variable_credentials_provider.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"environment_variable_credentials_provider.js","sourceRoot":"","sources":["../../../src/provider/environment_variable_credentials_provider.ts"],"names":[],"mappings":";;;;;AACA,qFAA2D;AAG3D,kBAAe;IACb,aAAa;QACX,MAAM,WAAW,GAAG,OAAO,CAAC,GAAG,CAAC,2BAA2B,CAAC;QAC5D,MAAM,eAAe,GAAG,OAAO,CAAC,GAAG,CAAC,+BAA+B,CAAC;QAEpE,IAAI,WAAW,KAAK,SAAS,IAAI,eAAe,KAAK,SAAS,EAAE;YAC9D,OAAO,IAAI,CAAC;SACb;QAED,IAAI,WAAW,KAAK,IAAI,IAAI,WAAW,KAAK,EAAE,EAAE;YAC9C,MAAM,IAAI,KAAK,CAAC,kEAAkE,CAAC,CAAC;SACrF;QAED,IAAI,eAAe,KAAK,IAAI,IAAI,eAAe,KAAK,EAAE,EAAE;YACtD,MAAM,IAAI,KAAK,CAAC,sEAAsE,CAAC,CAAC;SACzF;QAED,OAAO,IAAI,+BAAmB,CAAC,WAAW,EAAE,eAAe,CAAC,CAAC;IAC/D,CAAC;CACF,CAAA"}

View File

@@ -0,0 +1,5 @@
import ICredential from '../icredential';
declare const _default: {
getCredential(): ICredential;
};
export default _default;

View File

@@ -0,0 +1,17 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const ecs_ram_role_credential_1 = __importDefault(require("../ecs_ram_role_credential"));
exports.default = {
getCredential() {
const roleName = process.env.ALIBABA_CLOUD_ECS_METADATA;
const enableIMDSv2 = process.env.ALIBABA_CLOUD_ECS_IMDSV2_ENABLE;
if (roleName && roleName.length) {
return new ecs_ram_role_credential_1.default(roleName, {}, enableIMDSv2 && enableIMDSv2.toLowerCase() === 'true');
}
return null;
}
};
//# sourceMappingURL=instance_ram_role_credentials_provider.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"instance_ram_role_credentials_provider.js","sourceRoot":"","sources":["../../../src/provider/instance_ram_role_credentials_provider.ts"],"names":[],"mappings":";;;;;AAIA,yFAA8D;AAE9D,kBAAe;IACb,aAAa;QACX,MAAM,QAAQ,GAAG,OAAO,CAAC,GAAG,CAAC,0BAA0B,CAAC;QACxD,MAAM,YAAY,GAAG,OAAO,CAAC,GAAG,CAAC,+BAA+B,CAAC;QACjE,IAAI,QAAQ,IAAI,QAAQ,CAAC,MAAM,EAAE;YAC/B,OAAO,IAAI,iCAAoB,CAAC,QAAQ,EAAE,EAAE,EAAE,YAAY,IAAI,YAAY,CAAC,WAAW,EAAE,KAAK,MAAM,CAAC,CAAC;SACtG;QAED,OAAO,IAAI,CAAC;IACd,CAAC;CACF,CAAA"}

View File

@@ -0,0 +1,5 @@
import ICredential from '../icredential';
declare const _default: {
getCredential(): ICredential;
};
export default _default;

View File

@@ -0,0 +1,18 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const oidc_role_arn_credential_1 = __importDefault(require("../oidc_role_arn_credential"));
const config_1 = __importDefault(require("../config"));
exports.default = {
getCredential() {
if (process.env.ALIBABA_CLOUD_ROLE_ARN
&& process.env.ALIBABA_CLOUD_OIDC_PROVIDER_ARN
&& process.env.ALIBABA_CLOUD_OIDC_TOKEN_FILE) {
return new oidc_role_arn_credential_1.default(new config_1.default({}));
}
return null;
}
};
//# sourceMappingURL=oidc_role_arn_credentials_provider.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"oidc_role_arn_credentials_provider.js","sourceRoot":"","sources":["../../../src/provider/oidc_role_arn_credentials_provider.ts"],"names":[],"mappings":";;;;;AAIA,2FAAgE;AAChE,uDAA+B;AAE/B,kBAAe;IACb,aAAa;QACX,IAAI,OAAO,CAAC,GAAG,CAAC,sBAAsB;eACjC,OAAO,CAAC,GAAG,CAAC,+BAA+B;eAC3C,OAAO,CAAC,GAAG,CAAC,6BAA6B,EAAE;YAC9C,OAAO,IAAI,kCAAqB,CAAC,IAAI,gBAAM,CAAC,EAAE,CAAC,CAAC,CAAC;SAClD;QAED,OAAO,IAAI,CAAC;IACd,CAAC;CACF,CAAA"}

View File

@@ -0,0 +1,5 @@
import ICredential from '../icredential';
declare const _default: {
getCredential(credentialName?: string): ICredential;
};
export default _default;

View File

@@ -0,0 +1,100 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const access_key_credential_1 = __importDefault(require("../access_key_credential"));
const sts_token_credential_1 = __importDefault(require("../sts_token_credential"));
const ecs_ram_role_credential_1 = __importDefault(require("../ecs_ram_role_credential"));
const ram_role_arn_credential_1 = __importDefault(require("../ram_role_arn_credential"));
const oidc_role_arn_credential_1 = __importDefault(require("../oidc_role_arn_credential"));
const rsa_key_pair_credential_1 = __importDefault(require("../rsa_key_pair_credential"));
const bearer_token_credential_1 = __importDefault(require("../bearer_token_credential"));
const utils = __importStar(require("../util/utils"));
const fs_1 = __importDefault(require("fs"));
const config_1 = __importDefault(require("../config"));
const DEFAULT_PATH = process.env.HOME + '/.alibabacloud/credentials';
exports.default = {
getCredential(credentialName = 'default') {
let fileContent = null;
const credentialFile = process.env.ALIBABA_CLOUD_CREDENTIALS_FILE;
if (credentialFile === undefined) {
if (fs_1.default.existsSync(DEFAULT_PATH)) {
const content = utils.parseFile(DEFAULT_PATH, true);
if (content) {
fileContent = content;
}
}
}
else {
if (credentialFile === null || credentialFile === '') {
throw new Error('Environment variable credentialFile cannot be empty');
}
if (!fs_1.default.existsSync(credentialFile)) {
throw new Error(`credentialFile ${credentialFile} cannot be empty`);
}
fileContent = utils.parseFile(credentialFile);
}
if (!fileContent) {
return null;
}
const config = fileContent[credentialName] || {};
if (!config.type) {
throw new Error('Missing required type option in credentialFile');
}
switch (config.type) {
case 'access_key':
return new access_key_credential_1.default(config.access_key_id, config.access_key_secret);
case 'sts':
return new sts_token_credential_1.default(config.access_key_id, config.access_key_secret, config.security_token);
case 'ecs_ram_role':
return new ecs_ram_role_credential_1.default(config.role_name);
case 'ram_role_arn': {
const conf = new config_1.default({
roleArn: config.role_arn,
accessKeyId: config.access_key_id,
accessKeySecret: config.access_key_secret
});
return new ram_role_arn_credential_1.default(conf);
}
case 'oidc_role_arn': {
const conf = new config_1.default({
roleArn: config.role_arn,
oidcProviderArn: config.oidc_provider_arn,
oidcTokenFilePath: config.oidc_token_file_path
});
return new oidc_role_arn_credential_1.default(conf);
}
case 'rsa_key_pair':
return new rsa_key_pair_credential_1.default(config.public_key_id, config.private_key_file);
case 'bearer':
return new bearer_token_credential_1.default(config.bearer_token);
default:
throw new Error('Invalid type option, support: access_key, sts, ecs_ram_role, ram_role_arn, oidc_role_arn, rsa_key_pair, bearer');
}
}
};
//# sourceMappingURL=profile_credentials_provider.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"profile_credentials_provider.js","sourceRoot":"","sources":["../../../src/provider/profile_credentials_provider.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,qFAA2D;AAC3D,mFAAyD;AACzD,yFAA8D;AAC9D,yFAA8D;AAC9D,2FAAgE;AAChE,yFAA8D;AAC9D,yFAA+D;AAE/D,qDAAuC;AACvC,4CAAoB;AAEpB,uDAA+B;AAE/B,MAAM,YAAY,GAAG,OAAO,CAAC,GAAG,CAAC,IAAI,GAAG,4BAA4B,CAAC;AAErE,kBAAe;IACb,aAAa,CAAC,iBAAyB,SAAS;QAC9C,IAAI,WAAW,GAAG,IAAI,CAAC;QACvB,MAAM,cAAc,GAAG,OAAO,CAAC,GAAG,CAAC,8BAA8B,CAAC;QAClE,IAAI,cAAc,KAAK,SAAS,EAAE;YAChC,IAAI,YAAE,CAAC,UAAU,CAAC,YAAY,CAAC,EAAE;gBAC/B,MAAM,OAAO,GAAG,KAAK,CAAC,SAAS,CAAC,YAAY,EAAE,IAAI,CAAC,CAAC;gBACpD,IAAI,OAAO,EAAE;oBACX,WAAW,GAAG,OAAO,CAAC;iBACvB;aACF;SACF;aAAM;YACL,IAAI,cAAc,KAAK,IAAI,IAAI,cAAc,KAAK,EAAE,EAAE;gBACpD,MAAM,IAAI,KAAK,CAAC,qDAAqD,CAAC,CAAC;aACxE;YACD,IAAI,CAAC,YAAE,CAAC,UAAU,CAAC,cAAc,CAAC,EAAE;gBAClC,MAAM,IAAI,KAAK,CAAC,kBAAkB,cAAc,kBAAkB,CAAC,CAAC;aACrE;YACD,WAAW,GAAG,KAAK,CAAC,SAAS,CAAC,cAAc,CAAC,CAAC;SAC/C;QAED,IAAI,CAAC,WAAW,EAAE;YAChB,OAAO,IAAI,CAAC;SACb;QAED,MAAM,MAAM,GAAG,WAA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MAAM,IAAI,KAAK,CAAC,gHAAgH,CAAC,CAAC;SACnI;IACH,CAAC;CACF,CAAA"}

View File

@@ -0,0 +1,6 @@
import ICredential from '../icredential';
type IProvider = {
getCredential: () => ICredential;
};
export declare function getCredentials(providers?: IProvider[]): ICredential;
export {};

View File

@@ -0,0 +1,30 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getCredentials = void 0;
const environment_variable_credentials_provider_1 = __importDefault(require("./environment_variable_credentials_provider"));
const profile_credentials_provider_1 = __importDefault(require("./profile_credentials_provider"));
const instance_ram_role_credentials_provider_1 = __importDefault(require("./instance_ram_role_credentials_provider"));
const credentials_uri_provider_1 = __importDefault(require("./credentials_uri_provider"));
const oidc_role_arn_credentials_provider_1 = __importDefault(require("./oidc_role_arn_credentials_provider"));
const defaultProviders = [
environment_variable_credentials_provider_1.default,
oidc_role_arn_credentials_provider_1.default,
profile_credentials_provider_1.default,
instance_ram_role_credentials_provider_1.default,
credentials_uri_provider_1.default
];
function getCredentials(providers = null) {
const providerChain = providers || defaultProviders;
for (const provider of providerChain) {
const credential = provider.getCredential();
if (credential) {
return credential;
}
}
throw new Error('Not found credentials');
}
exports.getCredentials = getCredentials;
//# sourceMappingURL=provider_chain.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"provider_chain.js","sourceRoot":"","sources":["../../../src/provider/provider_chain.ts"],"names":[],"mappings":";;;;;;AAAA,4HAAiG;AACjG,kGAAwE;AACxE,sHAA0F;AAC1F,0FAAgE;AAChE,8GAAkF;AAQlF,MAAM,gBAAgB,GAAiB;IACrC,mDAAsC;IACtC,4CAA8B;IAC9B,sCAA0B;IAC1B,gDAAkC;IAClC,kCAAsB;CACvB,CAAC;AAEF,SAAgB,cAAc,CAAC,YAAyB,IAAI;IAC1D,MAAM,aAAa,GAAG,SAAS,IAAI,gBAAgB,CAAC;IACpD,KAAK,MAAM,QAAQ,IAAI,aAAa,EAAE;QACpC,MAAM,UAAU,GAAG,QAAQ,CAAC,aAAa,EAAE,CAAC;QAC5C,IAAI,UAAU,EAAE;YACd,OAAO,UAAU,CAAC;SACnB;KACF;IAED,MAAM,IAAI,KAAK,CAAC,uBAAuB,CAAC,CAAC;AAC3C,CAAC;AAVD,wCAUC"}

View File

@@ -0,0 +1,43 @@
import Credentials from '../credentials';
import CredentialsProvider from '../credentials_provider';
declare class CLIProfileCredentialsProviderBuilder {
profileName: string;
build(): CLIProfileCredentialsProvider;
withProfileName(profileName: string): this;
}
interface Profile {
name: string;
mode: string;
access_key_id: string;
access_key_secret: string;
sts_token: string;
region_id: string;
ram_role_arn: string;
ram_session_name: string;
expired_seconds: number;
sts_region: string;
source_profile: string;
ram_role_name: string;
oidc_token_file: string;
oidc_provider_arn: string;
sts_endpoint: string;
enable_vpc: boolean;
duration_seconds: number;
}
declare class Configuration {
current: string;
profiles: Profile[];
}
export declare function getConfiguration(cfgPath: string): Promise<Configuration>;
export declare function getProfile(conf: Configuration, profileName: string): Profile;
export default class CLIProfileCredentialsProvider implements CredentialsProvider {
static builder(): CLIProfileCredentialsProviderBuilder;
private readonly profileName;
private innerProvider;
private homedir;
constructor(builder: CLIProfileCredentialsProviderBuilder);
private getCredentialsProvider;
getCredentials(): Promise<Credentials>;
getProviderName(): string;
}
export {};

View File

@@ -0,0 +1,157 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getProfile = exports.getConfiguration = void 0;
const fs_1 = require("fs");
const util_1 = require("util");
const path_1 = __importDefault(require("path"));
const os_1 = __importDefault(require("os"));
const credentials_1 = __importDefault(require("../credentials"));
const static_ak_1 = __importDefault(require("./static_ak"));
const static_sts_1 = __importDefault(require("./static_sts"));
const ram_role_arn_1 = __importDefault(require("./ram_role_arn"));
const oidc_role_arn_1 = __importDefault(require("./oidc_role_arn"));
const ecs_ram_role_1 = __importDefault(require("./ecs_ram_role"));
const readFileAsync = (0, util_1.promisify)(fs_1.readFile);
class CLIProfileCredentialsProviderBuilder {
build() {
// 优先级:
// 1. 使用显示指定的 profileName
// 2. 使用环境变量ALIBABA_CLOUD_PROFILE制定的 profileName
// 3. 使用 CLI 配置中的当前 profileName
if (!this.profileName) {
this.profileName = process.env.ALIBABA_CLOUD_PROFILE;
}
if (process.env.ALIBABA_CLOUD_CLI_PROFILE_DISABLED && process.env.ALIBABA_CLOUD_CLI_PROFILE_DISABLED.toLowerCase() === 'true') {
throw new Error('the CLI profile is disabled');
}
return new CLIProfileCredentialsProvider(this);
}
withProfileName(profileName) {
this.profileName = profileName;
return this;
}
}
class Configuration {
}
async function getConfiguration(cfgPath) {
let content;
try {
content = await readFileAsync(cfgPath, 'utf8');
}
catch (ex) {
throw new Error(`reading aliyun cli config from '${cfgPath}' failed.`);
}
let conf;
try {
conf = JSON.parse(content);
}
catch (ex) {
throw new Error(`parse aliyun cli config from '${cfgPath}' failed: ${content}`);
}
if (!conf || !conf.profiles || conf.profiles.length === 0) {
throw new Error(`no any configured profiles in '${cfgPath}'`);
}
return conf;
}
exports.getConfiguration = getConfiguration;
function getProfile(conf, profileName) {
for (const p of conf.profiles) {
if (p.name === profileName) {
return p;
}
}
throw new Error(`unable to get profile with '${profileName}'`);
}
exports.getProfile = getProfile;
class CLIProfileCredentialsProvider {
static builder() {
return new CLIProfileCredentialsProviderBuilder();
}
constructor(builder) {
// used for mock
this.homedir = os_1.default.homedir();
this.profileName = builder.profileName;
}
getCredentialsProvider(conf, profileName) {
const p = getProfile(conf, profileName);
switch (p.mode) {
case 'AK':
return static_ak_1.default.builder()
.withAccessKeyId(p.access_key_id)
.withAccessKeySecret(p.access_key_secret)
.build();
case 'StsToken':
return static_sts_1.default.builder()
.withAccessKeyId(p.access_key_id)
.withAccessKeySecret(p.access_key_secret)
.withSecurityToken(p.sts_token)
.build();
case 'RamRoleArn': {
const previousProvider = static_ak_1.default.builder()
.withAccessKeyId(p.access_key_id)
.withAccessKeySecret(p.access_key_secret)
.build();
return ram_role_arn_1.default.builder()
.withCredentialsProvider(previousProvider)
.withRoleArn(p.ram_role_arn)
.withRoleSessionName(p.ram_session_name)
.withDurationSeconds(p.expired_seconds)
.withStsRegionId(p.sts_region)
.withStsEndpoint(p.sts_endpoint)
.withEnableVpc(p.enable_vpc)
.build();
}
case 'EcsRamRole':
return ecs_ram_role_1.default.builder().withRoleName(p.ram_role_name).build();
case 'OIDC':
return oidc_role_arn_1.default.builder()
.withOIDCTokenFilePath(p.oidc_token_file)
.withOIDCProviderArn(p.oidc_provider_arn)
.withRoleArn(p.ram_role_arn)
.withStsRegionId(p.sts_region)
.withDurationSeconds(p.expired_seconds)
.withRoleSessionName(p.ram_session_name)
.withDurationSeconds(p.duration_seconds)
.withEnableVpc(p.enable_vpc)
.build();
case 'ChainableRamRoleArn': {
const previousProvider = this.getCredentialsProvider(conf, p.source_profile);
return ram_role_arn_1.default.builder()
.withCredentialsProvider(previousProvider)
.withRoleArn(p.ram_role_arn)
.withRoleSessionName(p.ram_session_name)
.withDurationSeconds(p.expired_seconds)
.withStsRegionId(p.sts_region)
.build();
}
default:
throw new Error(`unsupported profile mode '${p.mode}'`);
}
}
async getCredentials() {
if (!this.innerProvider) {
if (!this.homedir) {
throw new Error('cannot found home dir');
}
const cfgPath = path_1.default.join(this.homedir, '.aliyun/config.json');
const conf = await getConfiguration(cfgPath);
const profileName = this.profileName || conf.current;
this.innerProvider = this.getCredentialsProvider(conf, profileName);
}
const credentials = await this.innerProvider.getCredentials();
return credentials_1.default.builder()
.withAccessKeyId(credentials.accessKeyId)
.withAccessKeySecret(credentials.accessKeySecret)
.withSecurityToken(credentials.securityToken)
.withProviderName(`${this.getProviderName()}/${this.innerProvider.getProviderName()}`)
.build();
}
getProviderName() {
return 'cli_profile';
}
}
exports.default = CLIProfileCredentialsProvider;
//# sourceMappingURL=cli_profile.js.map

View File

@@ -0,0 +1 @@
{"version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AC,eAAe,CAAC;aAChD,iBAAiB,CAAC,WAAW,CAAC,aAAa,CAAC;aAC5C,gBAAgB,CAAC,GAAG,IAAI,CAAC,eAAe,EAAE,IAAI,IAAI,CAAC,aAAa,CAAC,eAAe,EAAE,EAAE,CAAC;aACrF,KAAK,EAAE,CAAC;IACb,CAAC;IAED,eAAe;QACb,OAAO,aAAa,CAAC;IACvB,CAAC;CAEF;AAlGD,gDAkGC"}

View File

@@ -0,0 +1,14 @@
import Credentials from '../credentials';
import CredentialsProvider from '../credentials_provider';
export default class DefaultCredentialsProvider implements CredentialsProvider {
private readonly providers;
private lastUsedProvider;
static builder(): DefaultCredentialsProviderBuilder;
constructor(builder: DefaultCredentialsProviderBuilder);
getCredentials(): Promise<Credentials>;
getProviderName(): string;
}
declare class DefaultCredentialsProviderBuilder {
build(): DefaultCredentialsProvider;
}
export {};

View File

@@ -0,0 +1,112 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const credentials_1 = __importDefault(require("../credentials"));
const cli_profile_1 = __importDefault(require("./cli_profile"));
const ecs_ram_role_1 = __importDefault(require("./ecs_ram_role"));
const env_1 = __importDefault(require("./env"));
const oidc_role_arn_1 = __importDefault(require("./oidc_role_arn"));
const uri_1 = __importDefault(require("./uri"));
const profile_1 = __importDefault(require("./profile"));
class DefaultCredentialsProvider {
static builder() {
return new DefaultCredentialsProviderBuilder();
}
constructor(builder) {
this.providers = [];
// Add static ak or sts credentials provider from env
try {
const envProvider = env_1.default.builder().build();
this.providers.push(envProvider);
}
catch (ex) {
// ignore
}
// oidc check
try {
const oidcProvider = oidc_role_arn_1.default.builder().build();
this.providers.push(oidcProvider);
}
catch (ex) {
// ignore
}
// cli credentials provider
try {
const cliProfileProvider = cli_profile_1.default.builder().build();
this.providers.push(cliProfileProvider);
}
catch (ex) {
// ignore
}
// profile credentials provider
try {
const profileProvider = profile_1.default.builder().build();
this.providers.push(profileProvider);
}
catch (ex) {
// ignore
}
// Add IMDS
try {
const ecsRamRoleProvider = ecs_ram_role_1.default.builder().withRoleName(process.env.ALIBABA_CLOUD_ECS_METADATA).build();
this.providers.push(ecsRamRoleProvider);
}
catch (ex) {
// ignore
}
// credentials uri
try {
const uriProvider = uri_1.default.builder().withCredentialsURI(process.env.ALIBABA_CLOUD_CREDENTIALS_URI).build();
this.providers.push(uriProvider);
}
catch (ex) {
// ignore
}
}
async getCredentials() {
if (this.lastUsedProvider) {
const inner = await this.lastUsedProvider.getCredentials();
return credentials_1.default.builder()
.withAccessKeyId(inner.accessKeyId)
.withAccessKeySecret(inner.accessKeySecret)
.withSecurityToken(inner.securityToken)
.withProviderName(`${this.getProviderName()}/${this.lastUsedProvider.getProviderName()}`)
.build();
}
const errors = [];
for (const provider of this.providers) {
this.lastUsedProvider = provider;
let inner;
try {
inner = await provider.getCredentials();
}
catch (ex) {
errors.push(ex);
continue;
}
if (inner) {
return credentials_1.default.builder()
.withAccessKeyId(inner.accessKeyId)
.withAccessKeySecret(inner.accessKeySecret)
.withSecurityToken(inner.securityToken)
.withProviderName(`${this.getProviderName()}/${this.lastUsedProvider.getProviderName()}`)
.build();
}
}
throw new Error(`unable to get credentials from any of the providers in the chain: ${errors.map((e) => {
return e.message;
}).join(', ')}`);
}
getProviderName() {
return 'default';
}
}
exports.default = DefaultCredentialsProvider;
class DefaultCredentialsProviderBuilder {
build() {
return new DefaultCredentialsProvider(this);
}
}
//# sourceMappingURL=default.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"default.js","sourceRoot":"","sources":["../../../src/providers/default.ts"],"names":[],"mappings":";;;;;AAAA,iEAAyC;AAEzC,gEAA0D;AAC1D,kEAA2D;AAC3D,gDAA2D;AAC3D,oEAA6D;AAC7D,gDAA2C;AAC3C,wDAAmD;AAEnD,MAAqB,0BAA0B;IAG7C,MAAM,CAAC,OAAO;QACZ,OAAO,IAAI,iCAAiC,EAAE,CAAC;IACjD,CA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AAgB,CAAC,eAAe,EAAE,EAAE,CAAC;qBACxF,KAAK,EAAE,CAAC;aACZ;SACF;QAED,MAAM,IAAI,KAAK,CAAC,qEAAqE,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE;YACpG,OAAO,CAAC,CAAC,OAAO,CAAC;QACnB,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;IACnB,CAAC;IAED,eAAe;QACb,OAAO,SAAS,CAAC;IACnB,CAAC;CACF;AAlGD,6CAkGC;AAED,MAAM,iCAAiC;IACrC,KAAK;QACH,OAAO,IAAI,0BAA0B,CAAC,IAAI,CAAC,CAAC;IAC9C,CAAC;CACF"}

View File

@@ -0,0 +1,35 @@
/// <reference types="node" />
import CredentialsProvider from '../credentials_provider';
import { SessionCredentialProvider } from './session';
export default class ECSRAMRoleCredentialsProvider extends SessionCredentialProvider implements CredentialsProvider {
private readonly roleName;
private readonly disableIMDSv1;
private checker;
private doRequest;
private readonly readTimeout;
private readonly connectTimeout;
private shouldRefreshCred;
static builder(): ECSRAMRoleCredentialsProviderBuilder;
constructor(builder: ECSRAMRoleCredentialsProviderBuilder);
checkCredentialsUpdateAsynchronously(): NodeJS.Timeout;
close(): void;
private getMetadataToken;
private getRoleName;
private getCredentialsInternal;
getProviderName(): string;
}
declare class ECSRAMRoleCredentialsProviderBuilder {
roleName: string;
disableIMDSv1: boolean;
readTimeout?: number;
connectTimeout?: number;
asyncCredentialUpdateEnabled?: boolean;
constructor();
withRoleName(roleName: string): ECSRAMRoleCredentialsProviderBuilder;
withDisableIMDSv1(disableIMDSv1: boolean): ECSRAMRoleCredentialsProviderBuilder;
withReadTimeout(readTimeout: number): ECSRAMRoleCredentialsProviderBuilder;
withConnectTimeout(connectTimeout: number): ECSRAMRoleCredentialsProviderBuilder;
withAsyncCredentialUpdateEnabled(asyncCredentialUpdateEnabled: boolean): ECSRAMRoleCredentialsProviderBuilder;
build(): ECSRAMRoleCredentialsProvider;
}
export {};

View File

@@ -0,0 +1,187 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const http_1 = require("./http");
const session_1 = require("./session");
const PREFETCH_TIME = 60 * 60;
const defaultMetadataTokenDuration = 21600; // 6 hours
class ECSRAMRoleCredentialsProvider extends session_1.SessionCredentialProvider {
static builder() {
return new ECSRAMRoleCredentialsProviderBuilder();
}
constructor(builder) {
super(session_1.STALE_TIME, PREFETCH_TIME);
// for mock
this.doRequest = http_1.doRequest;
this.refresher = this.getCredentialsInternal;
this.roleName = builder.roleName;
this.disableIMDSv1 = builder.disableIMDSv1;
this.readTimeout = builder.readTimeout;
this.connectTimeout = builder.connectTimeout;
this.checker = null;
this.shouldRefreshCred = false;
if (builder.asyncCredentialUpdateEnabled) {
this.checker = this.checkCredentialsUpdateAsynchronously();
}
}
checkCredentialsUpdateAsynchronously() {
return setTimeout(async () => {
try {
if (this.shouldRefreshCred) {
await this.getCredentials();
}
}
catch (err) {
console.error('CheckCredentialsUpdateAsynchronously Error:', err);
}
finally {
this.checker = this.checkCredentialsUpdateAsynchronously();
}
}, 1000 * 60);
}
close() {
if (this.checker != null) {
clearTimeout(this.checker);
this.checker = null;
}
}
async getMetadataToken() {
// PUT http://100.100.100.200/latest/api/token
const request = http_1.Request.builder()
.withMethod('PUT')
.withProtocol('http')
.withHost('100.100.100.200')
.withPath('/latest/api/token')
.withHeaders({
'x-aliyun-ecs-metadata-token-ttl-seconds': `${defaultMetadataTokenDuration}`
})
.withReadTimeout(this.readTimeout || 1000)
.withConnectTimeout(this.connectTimeout || 1000)
.build();
// ConnectTimeout: 5 * time.Second,
// ReadTimeout: 5 * time.Second,
try {
const response = await this.doRequest(request);
if (response.statusCode !== 200) {
throw new Error(`get metadata token failed with ${response.statusCode}`);
}
return response.body.toString('utf8');
}
catch (error) {
if (this.disableIMDSv1) {
throw error;
}
return null;
}
}
async getRoleName() {
const builder = http_1.Request.builder()
.withMethod('GET')
.withProtocol('http')
.withHost('100.100.100.200')
.withPath('/latest/meta-data/ram/security-credentials/')
.withReadTimeout(this.readTimeout || 1000)
.withConnectTimeout(this.connectTimeout || 1000);
const metadataToken = await this.getMetadataToken();
if (metadataToken !== null) {
builder.withHeaders({
'x-aliyun-ecs-metadata-token': metadataToken
});
}
// ConnectTimeout: 5 * time.Second,
// ReadTimeout: 5 * time.Second,
const request = builder.build();
const response = await this.doRequest(request);
if (response.statusCode !== 200) {
throw new Error(`get role name failed: ${request.method} ${request.toRequestURL()} ${response.statusCode}`);
}
return response.body.toString().trim();
}
async getCredentialsInternal() {
let roleName = this.roleName;
if (!roleName) {
roleName = await this.getRoleName();
}
const builder = http_1.Request.builder()
.withMethod('GET')
.withProtocol('http')
.withHost('100.100.100.200')
.withPath(`/latest/meta-data/ram/security-credentials/${roleName}`)
.withReadTimeout(this.readTimeout || 1000)
.withConnectTimeout(this.connectTimeout || 1000);
// ConnectTimeout: 5 * time.Second,
// ReadTimeout: 5 * time.Second,
// Headers: map[string]string{ },
const metadataToken = await this.getMetadataToken();
if (metadataToken !== null) {
builder.withHeaders({
'x-aliyun-ecs-metadata-token': metadataToken
});
}
const request = builder.build();
const response = await this.doRequest(request);
if (response.statusCode !== 200) {
throw new Error(`get sts token failed, httpStatus: ${response.statusCode}, message = ${response.body.toString()}`);
}
let data;
try {
data = JSON.parse(response.body.toString());
}
catch (ex) {
throw new Error(`get sts token failed, json parse failed: ${ex.message}`);
}
if (!data || !data.AccessKeyId || !data.AccessKeySecret || !data.SecurityToken) {
throw new Error('get sts token failed');
}
if (data.Code !== 'Success') {
throw new Error('refresh Ecs sts token err, Code is not Success');
}
this.shouldRefreshCred = true;
return new session_1.Session(data.AccessKeyId, data.AccessKeySecret, data.SecurityToken, data.Expiration);
}
getProviderName() {
return 'ecs_ram_role';
}
}
exports.default = ECSRAMRoleCredentialsProvider;
class ECSRAMRoleCredentialsProviderBuilder {
constructor() {
this.disableIMDSv1 = false;
this.asyncCredentialUpdateEnabled = false;
}
withRoleName(roleName) {
this.roleName = roleName;
return this;
}
withDisableIMDSv1(disableIMDSv1) {
this.disableIMDSv1 = disableIMDSv1;
return this;
}
withReadTimeout(readTimeout) {
this.readTimeout = readTimeout;
return this;
}
withConnectTimeout(connectTimeout) {
this.connectTimeout = connectTimeout;
return this;
}
withAsyncCredentialUpdateEnabled(asyncCredentialUpdateEnabled) {
this.asyncCredentialUpdateEnabled = asyncCredentialUpdateEnabled;
return this;
}
build() {
// 允许通过环境变量强制关闭 IMDS
if (process.env.ALIBABA_CLOUD_ECS_METADATA_DISABLED && process.env.ALIBABA_CLOUD_ECS_METADATA_DISABLED.toLowerCase() === 'true') {
throw new Error('IMDS credentials is disabled');
}
// 设置 roleName 默认值
if (!this.roleName) {
this.roleName = process.env.ALIBABA_CLOUD_ECS_METADATA;
}
// 允许通过环境变量强制关闭 V1
if (process.env.ALIBABA_CLOUD_IMDSV1_DISABLED && process.env.ALIBABA_CLOUD_IMDSV1_DISABLED.toLowerCase() === 'true') {
this.disableIMDSv1 = true;
}
return new ECSRAMRoleCredentialsProvider(this);
}
}
//# sourceMappingURL=ecs_ram_role.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,12 @@
import Credentials from '../credentials';
import CredentialsProvider from '../credentials_provider';
export default class EnvironmentVariableCredentialsProvider implements CredentialsProvider {
static builder(): EnvironmentVariableCredentialsProviderBuilder;
getCredentials(): Promise<Credentials>;
getProviderName(): string;
constructor(builder: EnvironmentVariableCredentialsProviderBuilder);
}
declare class EnvironmentVariableCredentialsProviderBuilder {
build(): EnvironmentVariableCredentialsProvider;
}
export {};

View File

@@ -0,0 +1,40 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const credentials_1 = __importDefault(require("../credentials"));
class EnvironmentVariableCredentialsProvider {
static builder() {
return new EnvironmentVariableCredentialsProviderBuilder();
}
async getCredentials() {
const accessKeyId = process.env.ALIBABA_CLOUD_ACCESS_KEY_ID;
if (!accessKeyId) {
throw new Error('unable to get credentials from enviroment variables, Access key ID must be specified via environment variable (ALIBABA_CLOUD_ACCESS_KEY_ID)');
}
const accessKeySecret = process.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET;
if (!accessKeySecret) {
throw new Error('unable to get credentials from enviroment variables, Access key secret must be specified via environment variable (ALIBABA_CLOUD_ACCESS_KEY_SECRET)');
}
const securityToken = process.env.ALIBABA_CLOUD_SECURITY_TOKEN;
return credentials_1.default.builder()
.withAccessKeyId(accessKeyId)
.withAccessKeySecret(accessKeySecret)
.withSecurityToken(securityToken)
.withProviderName(this.getProviderName())
.build();
}
getProviderName() {
return 'env';
}
constructor(builder) {
}
}
exports.default = EnvironmentVariableCredentialsProvider;
class EnvironmentVariableCredentialsProviderBuilder {
build() {
return new EnvironmentVariableCredentialsProvider(this);
}
}
//# sourceMappingURL=env.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"env.js","sourceRoot":"","sources":["../../../src/providers/env.ts"],"names":[],"mappings":";;;;;AAAA,iEAAyC;AAGzC,MAAqB,sCAAsC;IACzD,MAAM,CAAC,OAAO;QACZ,OAAO,IAAI,6CAA6C,EAAE,CAAC;IAC7D,CAAC;IAED,KAAK,CAAC,cAAc;QAClB,MAAM,WAAW,GAAG,OAAO,CAAC,GAAG,CAAC,2BAA2B,CAAC;QAC5D,IAAI,CAAC,WAAW,EAAE;YAChB,MAAM,IAAI,KAAK,CAAC,6IAA6I,CAAC,CAAA;SAC/J;QAED,MAAM,eAAe,GAAG,OAAO,CAAC,GAAG,CAAC,+BAA+B,CAAC;QACpE,IAAI,CAAC,eAAe,EAAE;YACpB,MAAM,IAAI,KAAK,CAAC,qJAAqJ,CAAC,CAAA;SACvK;QAED,MAAM,aAAa,GAAG,OAAO,CAAC,GAAG,CAAC,4BAA4B,CAAC;QAE/D,OAAO,qBAAW,CAAC,OAAO,EAAE;aACzB,eAAe,CAAC,WAAW,CAAC;aAC5B,mBAAmB,CAAC,eAAe,CAAC;aACpC,iBAAiB,CAAC,aAAa,CAAC;aAChC,gBAAgB,CAAC,IAAI,CAAC,eAAe,EAAE,CAAC;aACxC,KAAK,EAAE,CAAC;IACb,CAAC;IAGD,eAAe;QACb,OAAO,KAAK,CAAC;IACf,CAAC;IAED,YAAY,OAAsD;IAElE,CAAC;CACF;AAlCD,yDAkCC;AAED,MAAM,6CAA6C;IACjD,KAAK;QACH,OAAO,IAAI,sCAAsC,CAAC,IAAI,CAAC,CAAC;IAC1D,CAAC;CACF"}

View File

@@ -0,0 +1,85 @@
/// <reference types="node" />
/// <reference types="node" />
export declare class Request {
readonly queries: {
[key: string]: string;
};
readonly headers: {
[key: string]: string;
};
readonly method: string;
readonly protocol: any;
readonly host: any;
readonly path: any;
readonly bodyForm: {
[key: string]: string;
};
readonly bodyBytes: Buffer;
readonly url: string;
readonly readTimeout: number;
readonly connectTimeout: number;
static builder(): RequestBuilder;
constructor(builder: RequestBuilder);
toRequestURL(): string;
}
export declare class RequestBuilder {
method: string;
protocol: string;
host: string;
path: string;
queries: {
[key: string]: string;
};
headers: {
[key: string]: string;
};
bodyForm: {
[key: string]: string;
};
bodyBytes: Buffer;
readTimeout: number;
connectTimeout: number;
url: string;
build(): Request;
withMethod(method: string): this;
withProtocol(protocol: string): this;
withHost(host: string): this;
withPath(path: string): this;
withQueries(queries: {
[key: string]: string;
}): this;
withHeaders(headers: {
[key: string]: string;
}): this;
withBodyForm(bodyForm: {
[key: string]: string;
}): this;
withURL(url: string): this;
withReadTimeout(readTimeout: number): this;
withConnectTimeout(connectTimeout: number): this;
}
export declare class Response {
readonly statusCode: number;
readonly body: Buffer;
readonly headers: {
[key: string]: string;
};
static builder(): ResponseBuilder;
constructor(builder: ResponseBuilder);
}
declare class ResponseBuilder {
statusCode: number;
headers: {
[key: string]: string;
};
body: Buffer;
withStatusCode(statusCode: number): this;
withHeaders(headers: {
[key: string]: string;
}): this;
withBody(body: Buffer): this;
constructor();
build(): Response;
}
export declare function doRequest(req: Request): Promise<Response>;
export {};

View File

@@ -0,0 +1,158 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.doRequest = exports.Response = exports.RequestBuilder = exports.Request = void 0;
const httpx_1 = __importDefault(require("httpx"));
class Request {
static builder() {
return new RequestBuilder();
}
constructor(builder) {
this.method = builder.method;
this.protocol = builder.protocol;
this.host = builder.host;
this.path = builder.path;
this.queries = builder.queries;
this.headers = builder.headers;
this.bodyForm = builder.bodyForm;
this.bodyBytes = builder.bodyBytes;
this.url = builder.url;
this.readTimeout = builder.readTimeout;
this.connectTimeout = builder.connectTimeout;
}
toRequestURL() {
if (this.url) {
return this.url;
}
let url = `${this.protocol}://${this.host}${this.path}`;
if (this.queries && Object.keys(this.queries).length > 0) {
url += `?` + querystringify(this.queries);
}
return url;
}
}
exports.Request = Request;
class RequestBuilder {
build() {
// set default values
if (!this.protocol) {
this.protocol = 'https';
}
if (!this.path) {
this.path = '/';
}
if (!this.headers) {
this.headers = {};
}
if (!this.queries) {
this.queries = {};
}
return new Request(this);
}
withMethod(method) {
this.method = method;
return this;
}
withProtocol(protocol) {
this.protocol = protocol;
return this;
}
withHost(host) {
this.host = host;
return this;
}
withPath(path) {
this.path = path;
return this;
}
withQueries(queries) {
this.queries = queries;
return this;
}
withHeaders(headers) {
this.headers = headers;
return this;
}
withBodyForm(bodyForm) {
this.bodyForm = bodyForm;
return this;
}
withURL(url) {
this.url = url;
return this;
}
withReadTimeout(readTimeout) {
this.readTimeout = readTimeout;
return this;
}
withConnectTimeout(connectTimeout) {
this.connectTimeout = connectTimeout;
return this;
}
}
exports.RequestBuilder = RequestBuilder;
class Response {
static builder() {
return new ResponseBuilder();
}
constructor(builder) {
this.statusCode = builder.statusCode;
this.headers = builder.headers;
this.body = builder.body;
}
}
exports.Response = Response;
class ResponseBuilder {
withStatusCode(statusCode) {
this.statusCode = statusCode;
return this;
}
withHeaders(headers) {
this.headers = headers;
return this;
}
withBody(body) {
this.body = body;
return this;
}
constructor() {
this.headers = {};
}
build() {
return new Response(this);
}
}
function querystringify(queries) {
const fields = [];
for (const [key, value] of Object.entries(queries)) {
fields.push(key + '=' + encodeURIComponent(value));
}
return fields.join('&');
}
async function doRequest(req) {
const url = req.toRequestURL();
let body;
if (req.bodyForm && Object.keys(req.bodyForm).length > 0) {
body = querystringify(req.bodyForm);
if (!req.headers['Content-Type']) {
req.headers['Content-Type'] = 'application/x-www-form-urlencoded';
}
}
const response = await httpx_1.default.request(url, {
method: req.method,
data: body,
headers: req.headers,
readTimeout: req.readTimeout,
connectTimeout: req.connectTimeout
});
const responseBody = await httpx_1.default.read(response, '');
return Response.builder()
.withStatusCode(response.statusCode)
.withHeaders(response.headers)
.withBody(responseBody)
.build();
}
exports.doRequest = doRequest;
//# sourceMappingURL=http.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"http.js","sourceRoot":"","sources":["../../../src/providers/http.ts"],"names":[],"mappings":";;;;;;AAAA,kDAA0B;AAE1B,MAAa,OAAO;IAalB,MAAM,CAAC,OAAO;QACZ,OAAO,IAAI,cAAc,EAAE,CAAC;IAC9B,CAAC;IAED,YAAY,OAAuB;QACjC,IAAI,CAAC,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;QAC7B,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC,QAAQ,CAAC;QACjC,IAAI,CAAC,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;QACzB,IAAI,CAAC,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;QACzB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC;QAC/B,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC;QAC/B,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC,QAAQ,CAAC;QACjC,IAAI,CAAC,SAAS,GAAG,OAAO,CAAC,SAAS,CAAC;QACnC,IAAI,CAAC,GAAG,GAAG,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AAG,CAAC,MAAM;QAClB,IAAI,EAAE,IAAI;QACV,OAAO,EAAE,GAAG,CAAC,OAAO;QACpB,WAAW,EAAE,GAAG,CAAC,WAAW;QAC5B,cAAc,EAAE,GAAG,CAAC,cAAc;KACnC,CAAC,CAAC;IAEH,MAAM,YAAY,GAAG,MAAM,eAAK,CAAC,IAAI,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC;IACpD,OAAO,QAAQ,CAAC,OAAO,EAAE;SACtB,cAAc,CAAC,QAAQ,CAAC,UAAU,CAAC;SACnC,WAAW,CAAC,QAAQ,CAAC,OAAoC,CAAC;SAC1D,QAAQ,CAAC,YAAsB,CAAC;SAChC,KAAK,EAAE,CAAC;AACb,CAAC;AAzBD,8BAyBC"}

View File

@@ -0,0 +1,48 @@
import CredentialsProvider from '../credentials_provider';
import { Session, SessionCredentialProvider } from './session';
declare class OIDCRoleArnCredentialsProviderBuilder {
oidcProviderArn: any;
oidcTokenFilePath: any;
roleArn: any;
roleSessionName: string;
stsEndpoint: string;
stsRegionId: string;
policy: string;
durationSeconds: number;
enableVpc?: boolean;
readTimeout?: number;
connectTimeout?: number;
withOIDCProviderArn(oidcProviderArn: string): this;
withOIDCTokenFilePath(path: string): this;
withRoleArn(roleArn: string): this;
withRoleSessionName(roleSessionName: string): this;
withDurationSeconds(durationSeconds: number): this;
withStsEndpoint(stsEndpoint: string): this;
withStsRegionId(regionId: string): this;
withPolicy(policy: string): this;
withEnableVpc(enableVpc: boolean): OIDCRoleArnCredentialsProviderBuilder;
withReadTimeout(readTimeout: number): OIDCRoleArnCredentialsProviderBuilder;
withConnectTimeout(connectTimeout: number): OIDCRoleArnCredentialsProviderBuilder;
build(): OIDCRoleArnCredentialsProvider;
}
export default class OIDCRoleArnCredentialsProvider extends SessionCredentialProvider implements CredentialsProvider {
private readonly roleArn;
private readonly oidcProviderArn;
private readonly oidcTokenFilePath;
private readonly policy;
private readonly durationSeconds;
private readonly roleSessionName;
runtime: {
[key: string]: any;
};
private readonly stsEndpoint;
private doRequest;
private readonly readTimeout;
private readonly connectTimeout;
lastUpdateTimestamp: number;
static builder(): OIDCRoleArnCredentialsProviderBuilder;
constructor(builder: OIDCRoleArnCredentialsProviderBuilder);
getProviderName(): string;
getCredentialsInternal(): Promise<Session>;
}
export {};

View File

@@ -0,0 +1,201 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const fs_1 = require("fs");
const util_1 = require("util");
const session_1 = require("./session");
const utils = __importStar(require("../util/utils"));
const http_1 = require("./http");
const readFileAsync = (0, util_1.promisify)(fs_1.readFile);
class OIDCRoleArnCredentialsProviderBuilder {
withOIDCProviderArn(oidcProviderArn) {
this.oidcProviderArn = oidcProviderArn;
return this;
}
withOIDCTokenFilePath(path) {
this.oidcTokenFilePath = path;
return this;
}
withRoleArn(roleArn) {
this.roleArn = roleArn;
return this;
}
withRoleSessionName(roleSessionName) {
this.roleSessionName = roleSessionName;
return this;
}
withDurationSeconds(durationSeconds) {
this.durationSeconds = durationSeconds;
return this;
}
withStsEndpoint(stsEndpoint) {
this.stsEndpoint = stsEndpoint;
return this;
}
withStsRegionId(regionId) {
this.stsRegionId = regionId;
return this;
}
withPolicy(policy) {
this.policy = policy;
return this;
}
withEnableVpc(enableVpc) {
this.enableVpc = enableVpc;
return this;
}
withReadTimeout(readTimeout) {
this.readTimeout = readTimeout;
return this;
}
withConnectTimeout(connectTimeout) {
this.connectTimeout = connectTimeout;
return this;
}
build() {
// set default values
if (!this.oidcProviderArn) {
this.oidcProviderArn = process.env.ALIBABA_CLOUD_OIDC_PROVIDER_ARN;
}
if (!this.oidcTokenFilePath) {
this.oidcTokenFilePath = process.env.ALIBABA_CLOUD_OIDC_TOKEN_FILE;
}
if (!this.roleSessionName) {
this.roleSessionName = process.env.ALIBABA_CLOUD_ROLE_SESSION_NAME;
}
if (!this.durationSeconds) {
this.durationSeconds = 3600;
}
if (!this.roleArn) {
this.roleArn = process.env.ALIBABA_CLOUD_ROLE_ARN;
}
if (!this.roleArn) {
throw new Error('roleArn does not exist and env ALIBABA_CLOUD_ROLE_ARN is null.');
}
if (!this.oidcProviderArn) {
throw new Error('oidcProviderArn does not exist and env ALIBABA_CLOUD_OIDC_PROVIDER_ARN is null.');
}
if (!this.oidcTokenFilePath) {
throw new Error('oidcTokenFilePath is not exists and env ALIBABA_CLOUD_OIDC_TOKEN_FILE is null.');
}
if (!this.roleSessionName) {
this.roleSessionName = 'credentials-nodejs-' + Date.now();
}
if (this.durationSeconds < 900) {
throw new Error('session duration should be in the range of 900s - max session duration');
}
if (!this.stsRegionId) {
this.stsRegionId = process.env.ALIBABA_CLOUD_STS_REGION;
}
if (!this.enableVpc) {
this.enableVpc = process.env.ALIBABA_CLOUD_VPC_ENDPOINT_ENABLED && process.env.ALIBABA_CLOUD_VPC_ENDPOINT_ENABLED.toLowerCase() === 'true' || false;
}
// sts endpoint
if (!this.stsEndpoint) {
if (this.stsRegionId) {
if (this.enableVpc) {
this.stsEndpoint = `sts-vpc.${this.stsRegionId}.aliyuncs.com`;
}
else {
this.stsEndpoint = `sts.${this.stsRegionId}.aliyuncs.com`;
}
}
else {
this.stsEndpoint = 'sts.aliyuncs.com';
}
}
return new OIDCRoleArnCredentialsProvider(this);
}
}
class OIDCRoleArnCredentialsProvider extends session_1.SessionCredentialProvider {
static builder() {
return new OIDCRoleArnCredentialsProviderBuilder();
}
constructor(builder) {
super(session_1.STALE_TIME);
this.doRequest = http_1.doRequest;
this.refresher = this.getCredentialsInternal;
this.roleArn = builder.roleArn;
this.oidcProviderArn = builder.oidcProviderArn;
this.oidcTokenFilePath = builder.oidcTokenFilePath;
this.policy = builder.policy;
this.durationSeconds = builder.durationSeconds;
this.roleSessionName = builder.roleSessionName;
this.stsEndpoint = builder.stsEndpoint;
this.readTimeout = builder.readTimeout;
this.connectTimeout = builder.connectTimeout;
// used for mock
this.doRequest = http_1.doRequest;
}
getProviderName() {
return 'oidc_role_arn';
}
async getCredentialsInternal() {
const oidcToken = await readFileAsync(this.oidcTokenFilePath, 'utf8');
const builder = http_1.Request.builder().withMethod('POST').withProtocol('https').withHost(this.stsEndpoint).withReadTimeout(this.readTimeout || 10000).withConnectTimeout(this.connectTimeout || 5000);
const queries = Object.create(null);
queries['Version'] = '2015-04-01';
queries['Action'] = 'AssumeRoleWithOIDC';
queries['Format'] = 'JSON';
queries['Timestamp'] = utils.timestamp();
builder.withQueries(queries);
const bodyForm = Object.create(null);
bodyForm['OIDCProviderArn'] = this.oidcProviderArn;
bodyForm['OIDCToken'] = oidcToken;
bodyForm['RoleArn'] = this.roleArn;
if (this.policy) {
bodyForm['Policy'] = this.policy;
}
bodyForm['RoleSessionName'] = this.roleSessionName;
bodyForm['DurationSeconds'] = `${this.durationSeconds}`;
builder.withBodyForm(bodyForm);
const headers = Object.create(null);
// set headers
headers['Content-Type'] = 'application/x-www-form-urlencoded';
builder.withHeaders(headers);
const request = builder.build();
const response = await this.doRequest(request);
if (response.statusCode !== 200) {
throw new Error(`get sts token failed with OIDC: ${response.body.toString('utf8')}`);
}
let data;
try {
data = JSON.parse(response.body.toString('utf8'));
}
catch (ex) {
throw new Error(`get sts token failed with OIDC, unmarshal fail: ${response.body.toString('utf8')}`);
}
if (!data || !data.Credentials) {
throw new Error(`get sts token failed with OIDC`);
}
const { AccessKeyId, AccessKeySecret, SecurityToken, Expiration } = data.Credentials;
if (!AccessKeyId || !AccessKeySecret || !SecurityToken) {
throw new Error('get sts token failed with OIDC');
}
return new session_1.Session(AccessKeyId, AccessKeySecret, SecurityToken, Expiration);
}
}
exports.default = OIDCRoleArnCredentialsProvider;
//# sourceMappingURL=oidc_role_arn.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,18 @@
import Credentials from '../credentials';
import CredentialsProvider from '../credentials_provider';
export default class ProfileCredentialsProvider implements CredentialsProvider {
private readonly profileName;
private innerProvider;
private readonly homedir;
getCredentials(): Promise<Credentials>;
getCredentialsProvider(ini: any): CredentialsProvider;
getProviderName(): string;
static builder(): ProfileCredentialsProviderBuilder;
constructor(builder: ProfileCredentialsProviderBuilder);
}
declare class ProfileCredentialsProviderBuilder {
profileName: string;
withProfileName(profileName: string): this;
build(): ProfileCredentialsProvider;
}
export {};

View File

@@ -0,0 +1,99 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const path_1 = __importDefault(require("path"));
const os_1 = __importDefault(require("os"));
const credentials_1 = __importDefault(require("../credentials"));
const utils_1 = require("../util/utils");
const static_ak_1 = __importDefault(require("./static_ak"));
const ecs_ram_role_1 = __importDefault(require("./ecs_ram_role"));
const ram_role_arn_1 = __importDefault(require("./ram_role_arn"));
class ProfileCredentialsProvider {
async getCredentials() {
if (!this.innerProvider) {
let sharedCfgPath = process.env.ALIBABA_CLOUD_CREDENTIALS_FILE;
if (!sharedCfgPath) {
if (!this.homedir) {
throw new Error('cannot found home dir');
}
sharedCfgPath = path_1.default.join(this.homedir, '.alibabacloud/credentials');
}
const ini = await (0, utils_1.loadIni)(sharedCfgPath);
this.innerProvider = this.getCredentialsProvider(ini);
}
const credentials = await this.innerProvider.getCredentials();
return credentials_1.default.builder()
.withAccessKeyId(credentials.accessKeyId)
.withAccessKeySecret(credentials.accessKeySecret)
.withSecurityToken(credentials.securityToken)
.withProviderName(`${this.getProviderName()}/${this.innerProvider.getProviderName()}`)
.build();
}
getCredentialsProvider(ini) {
const config = ini[this.profileName] || {};
if (!config.type) {
throw new Error(`Can not find credential type for "${this.profileName}"`);
}
switch (config.type) {
case 'access_key':
return static_ak_1.default.builder()
.withAccessKeyId(config.access_key_id)
.withAccessKeySecret(config.access_key_secret)
.build();
case 'ecs_ram_role':
return ecs_ram_role_1.default.builder()
.withRoleName(config.role_name)
.build();
case 'ram_role_arn':
{
const previous = static_ak_1.default.builder()
.withAccessKeyId(config.access_key_id)
.withAccessKeySecret(config.access_key_secret)
.build();
return ram_role_arn_1.default.builder()
.withCredentialsProvider(previous)
.withRoleArn(config.role_arn)
.withRoleSessionName(config.role_session_name)
.withPolicy(config.policy)
// .withStsEndpoint(config.stsEndpoint)
// .withStsRegionId(config.stsRegionId)
// .withEnableVpc(config.enableVpc)
// .withExternalId(config.enableVpc)
.build();
}
default:
throw new Error('Invalid type option, support: access_key, ecs_ram_role, ram_role_arn');
}
}
getProviderName() {
return 'profile';
}
static builder() {
return new ProfileCredentialsProviderBuilder();
}
constructor(builder) {
// used for mock
this.homedir = os_1.default.homedir();
this.profileName = builder.profileName;
}
}
exports.default = ProfileCredentialsProvider;
class ProfileCredentialsProviderBuilder {
withProfileName(profileName) {
this.profileName = profileName;
return this;
}
build() {
// 优先级:
// 1. 使用显示指定的 profileName
// 2. 使用环境变量ALIBABA_CLOUD_PROFILE指定的 profileName
// 3. 兜底使用 default 作为 profileName
if (!this.profileName) {
this.profileName = process.env.ALIBABA_CLOUD_PROFILE || 'default';
}
return new ProfileCredentialsProvider(this);
}
}
//# sourceMappingURL=profile.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"profile.js","sourceRoot":"","sources":["../../../src/providers/profile.ts"],"names":[],"mappings":";;;;;AAAA,gD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C,eAAe,CAAC,WAAmB;QACjC,IAAI,CAAC,WAAW,GAAG,WAAW,CAAC;QAC/B,OAAO,IAAI,CAAC;IACd,CAAC;IAED,KAAK;QACH,OAAO;QACP,yBAAyB;QACzB,kDAAkD;QAClD,iCAAiC;QACjC,IAAI,CAAC,IAAI,CAAC,WAAW,EAAE;YACrB,IAAI,CAAC,WAAW,GAAG,OAAO,CAAC,GAAG,CAAC,qBAAqB,IAAI,SAAS,CAAC;SACnE;QAED,OAAO,IAAI,0BAA0B,CAAC,IAAI,CAAC,CAAC;IAC9C,CAAC;CAEF"}

View File

@@ -0,0 +1,45 @@
import CredentialsProvider from '../credentials_provider';
import { SessionCredentialProvider } from './session';
declare class RAMRoleARNCredentialsProviderBuilder {
credentialsProvider: CredentialsProvider;
roleArn: string;
roleSessionName: string;
durationSeconds: number;
stsEndpoint: string;
stsRegionId: string;
policy: string;
externalId: string;
enableVpc?: boolean;
readTimeout?: number;
connectTimeout?: number;
build(): RAMRoleARNCredentialsProvider;
withCredentialsProvider(credentialsProvider: CredentialsProvider): RAMRoleARNCredentialsProviderBuilder;
withRoleArn(roleArn: string): RAMRoleARNCredentialsProviderBuilder;
withStsRegionId(regionId: string): RAMRoleARNCredentialsProviderBuilder;
withStsEndpoint(endpoint: string): RAMRoleARNCredentialsProviderBuilder;
withRoleSessionName(roleSessionName: string): RAMRoleARNCredentialsProviderBuilder;
withPolicy(policy: string): RAMRoleARNCredentialsProviderBuilder;
withExternalId(externalId: string): RAMRoleARNCredentialsProviderBuilder;
withDurationSeconds(durationSeconds: number): RAMRoleARNCredentialsProviderBuilder;
withEnableVpc(enableVpc: boolean): RAMRoleARNCredentialsProviderBuilder;
withReadTimeout(readTimeout: number): RAMRoleARNCredentialsProviderBuilder;
withConnectTimeout(connectTimeout: number): RAMRoleARNCredentialsProviderBuilder;
}
export default class RAMRoleARNCredentialsProvider extends SessionCredentialProvider implements CredentialsProvider {
private readonly credentialsProvider;
private readonly stsEndpoint;
private readonly roleSessionName;
private readonly policy;
private readonly durationSeconds;
private readonly externalId;
private readonly roleArn;
private readonly readTimeout;
private readonly connectTimeout;
private doRequest;
private lastUpdateTimestamp;
static builder(): RAMRoleARNCredentialsProviderBuilder;
constructor(builder: RAMRoleARNCredentialsProviderBuilder);
private getCredentialsInternal;
getProviderName(): string;
}
export {};

View File

@@ -0,0 +1,242 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const kitx = __importStar(require("kitx"));
const debug_1 = __importDefault(require("debug"));
const utils = __importStar(require("../util/utils"));
const http_1 = require("./http");
const session_1 = require("./session");
const log = (0, debug_1.default)('sign');
// type HttpOptions struct {
// Proxy : string
// ConnectTimeout int
// ReadTimeout int
// }
class RAMRoleARNCredentialsProviderBuilder {
build() {
if (!this.credentialsProvider) {
throw new Error('must specify a previous credentials provider to asssume role');
}
if (!(this.roleArn = this.roleArn || process.env.ALIBABA_CLOUD_ROLE_ARN))
throw new Error('the RoleArn is empty');
if (!this.roleSessionName) {
this.roleSessionName = process.env.ALIBABA_CLOUD_ROLE_SESSION_NAME || 'credentials-nodejs-' + Date.now();
}
if (!this.stsRegionId) {
this.stsRegionId = process.env.ALIBABA_CLOUD_STS_REGION;
}
if (!this.enableVpc) {
this.enableVpc = process.env.ALIBABA_CLOUD_VPC_ENDPOINT_ENABLED && process.env.ALIBABA_CLOUD_VPC_ENDPOINT_ENABLED.toLowerCase() === 'true' || false;
}
// duration seconds
if (!this.durationSeconds) {
// default to 3600
this.durationSeconds = 3600;
}
if (this.durationSeconds < 900) {
throw new Error('session duration should be in the range of 900s - max session duration');
}
// sts endpoint
if (!this.stsEndpoint) {
if (this.stsRegionId) {
if (this.enableVpc) {
this.stsEndpoint = `sts-vpc.${this.stsRegionId}.aliyuncs.com`;
}
else {
this.stsEndpoint = `sts.${this.stsRegionId}.aliyuncs.com`;
}
}
else {
this.stsEndpoint = 'sts.aliyuncs.com';
}
}
return new RAMRoleARNCredentialsProvider(this);
}
withCredentialsProvider(credentialsProvider) {
this.credentialsProvider = credentialsProvider;
return this;
}
withRoleArn(roleArn) {
this.roleArn = roleArn;
return this;
}
withStsRegionId(regionId) {
this.stsRegionId = regionId;
return this;
}
withStsEndpoint(endpoint) {
this.stsEndpoint = endpoint;
return this;
}
withRoleSessionName(roleSessionName) {
this.roleSessionName = roleSessionName;
return this;
}
withPolicy(policy) {
this.policy = policy;
return this;
}
withExternalId(externalId) {
this.externalId = externalId;
return this;
}
withDurationSeconds(durationSeconds) {
this.durationSeconds = durationSeconds;
return this;
}
withEnableVpc(enableVpc) {
this.enableVpc = enableVpc;
return this;
}
withReadTimeout(readTimeout) {
this.readTimeout = readTimeout;
return this;
}
withConnectTimeout(connectTimeout) {
this.connectTimeout = connectTimeout;
return this;
}
}
function encode(str) {
const result = encodeURIComponent(str);
return result.replace(/!/g, '%21')
.replace(/'/g, '%27')
.replace(/\(/g, '%28')
.replace(/\)/g, '%29')
.replace(/\*/g, '%2A');
}
class RAMRoleARNCredentialsProvider extends session_1.SessionCredentialProvider {
static builder() {
return new RAMRoleARNCredentialsProviderBuilder();
}
constructor(builder) {
super(session_1.STALE_TIME);
// used for mock
this.doRequest = http_1.doRequest;
this.refresher = this.getCredentialsInternal;
this.credentialsProvider = builder.credentialsProvider;
this.stsEndpoint = builder.stsEndpoint;
this.roleSessionName = builder.roleSessionName;
this.policy = builder.policy;
this.durationSeconds = builder.durationSeconds;
this.roleArn = builder.roleArn;
this.externalId = builder.externalId;
this.readTimeout = builder.readTimeout;
this.connectTimeout = builder.connectTimeout;
}
async getCredentialsInternal() {
const credentials = await this.credentialsProvider.getCredentials();
const method = 'POST';
const builder = http_1.Request.builder().withMethod(method).withProtocol('https').withHost(this.stsEndpoint).withReadTimeout(this.readTimeout || 10000).withConnectTimeout(this.connectTimeout || 5000);
const queries = Object.create(null);
queries['Version'] = '2015-04-01';
queries['Action'] = 'AssumeRole';
queries['Format'] = 'JSON';
queries['Timestamp'] = utils.timestamp();
queries['SignatureMethod'] = 'HMAC-SHA1';
queries['SignatureVersion'] = '1.0';
queries['SignatureNonce'] = kitx.makeNonce();
queries['AccessKeyId'] = credentials.accessKeyId;
if (credentials.securityToken) {
queries['SecurityToken'] = credentials.securityToken;
}
const bodyForm = Object.create(null);
bodyForm['RoleArn'] = this.roleArn;
if (this.policy) {
bodyForm['Policy'] = this.policy;
}
if (this.externalId) {
bodyForm['ExternalId'] = this.externalId;
}
bodyForm['RoleSessionName'] = this.roleSessionName;
bodyForm['DurationSeconds'] = `${this.durationSeconds}`;
builder.withBodyForm(bodyForm);
// caculate signature
const signParams = Object.create(null);
for (const [key, value] of Object.entries(queries)) {
signParams[key] = value;
}
for (const [key, value] of Object.entries(bodyForm)) {
signParams[key] = value;
}
const keys = Object.keys(signParams).sort();
const stringToSign = `${method}&${encode('/')}&${encode(keys.map((key) => {
return `${encode(key)}=${encode(signParams[key])}`;
}).join('&'))}`;
log('stringToSign[Client]:');
log(stringToSign);
const secret = credentials.accessKeySecret + '&';
const signature = kitx.sha1(stringToSign, secret, 'base64');
queries['Signature'] = signature;
builder.withQueries(queries);
const headers = Object.create(null);
// set headers
headers['Content-Type'] = 'application/x-www-form-urlencoded';
headers['x-acs-credentials-provider'] = credentials.providerName;
builder.withHeaders(headers);
// if (this.httpOptions) {
// req.connectTimeout = this.httpOptions.connectTimeout;
// req.readTimeout = this.httpOptions.readTimeout;
// req.proxy = this.httpOptions.proxy;
// }
const request = builder.build();
const response = await this.doRequest(request);
if (response.statusCode != 200) {
if (response.headers['content-type'] && response.headers['content-type'].startsWith('application/json')) {
const body = JSON.parse(response.body.toString('utf8'));
const serverStringToSign = body.Message.slice('Specified signature is not matched with our calculation. server string to sign is:'.length);
log('stringToSign[Server]:');
log(stringToSign);
if (body.Code === 'SignatureDoesNotMatch' && serverStringToSign === stringToSign) {
throw new Error(`the access key secret is invalid`);
}
}
throw new Error(`refresh session token failed: ${response.body.toString('utf8')}`);
}
let data;
try {
data = JSON.parse(response.body.toString('utf8'));
}
catch (ex) {
throw new Error(`refresh RoleArn sts token err, unmarshal fail: ${response.body.toString('utf8')}`);
}
if (!data || !data.Credentials) {
throw new Error(`refresh RoleArn sts token err, fail to get credentials`);
}
if (!data.Credentials.AccessKeyId || !data.Credentials.AccessKeySecret || !data.Credentials.SecurityToken) {
throw new Error('refresh RoleArn sts token err, fail to get credentials');
}
const { AccessKeyId, AccessKeySecret, SecurityToken, Expiration } = data.Credentials;
return new session_1.Session(AccessKeyId, AccessKeySecret, SecurityToken, Expiration);
}
getProviderName() {
return `ram_role_arn/${this.credentialsProvider.getProviderName()}`;
}
}
exports.default = RAMRoleARNCredentialsProvider;
//# sourceMappingURL=ram_role_arn.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,31 @@
import CredentialsProvider from '../credentials_provider';
import Credentials from '../credentials';
export declare const STALE_TIME: number;
export declare class Session {
accessKeyId: string;
accessKeySecret: string;
securityToken: string;
expiration: string;
constructor(accessKeyId: string, accessKeySecret: string, securityToken: string, expiration: string);
}
export declare type SessionRefresher = () => Promise<Session>;
export declare class SessionCredentialProvider implements CredentialsProvider {
private expirationTimestamp;
private session;
private refreshFaliure;
private readonly staleTime;
private readonly prefetchTime;
private staleTimestamp;
private prefetchTimestamp;
refresher: SessionRefresher;
constructor(staleTime?: number, prefetchTime?: number);
getCredentials(): Promise<Credentials>;
refreshTimestamp(): void;
maxStaleFailureJitter(): number;
jitterTime(time: number, jitterStart: number, jitterEnd: number): number;
refreshSession(): Promise<void>;
getSession(): Promise<Session>;
needUpdateCredential(): boolean;
shouldPrefetchCredential(): boolean;
getProviderName(): string;
}

View File

@@ -0,0 +1,119 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.SessionCredentialProvider = exports.Session = exports.STALE_TIME = void 0;
const time_1 = require("./time");
const utils_1 = require("../util/utils");
const credentials_1 = __importDefault(require("../credentials"));
exports.STALE_TIME = 15 * 60;
class Session {
constructor(accessKeyId, accessKeySecret, securityToken, expiration) {
this.accessKeyId = accessKeyId;
this.accessKeySecret = accessKeySecret;
this.securityToken = securityToken;
this.expiration = expiration;
}
}
exports.Session = Session;
class SessionCredentialProvider {
constructor(staleTime = 0, prefetchTime = 0) {
this.staleTime = staleTime || exports.STALE_TIME;
if (prefetchTime) {
this.prefetchTime = prefetchTime;
this.prefetchTimestamp = Date.now() + (prefetchTime * 1000);
}
this.refreshFaliure = 0;
}
async getCredentials() {
this.session = await this.getSession();
return credentials_1.default.builder()
.withAccessKeyId(this.session.accessKeyId)
.withAccessKeySecret(this.session.accessKeySecret)
.withSecurityToken(this.session.securityToken)
.withProviderName(this.getProviderName())
.build();
}
refreshTimestamp() {
this.staleTimestamp = this.expirationTimestamp - this.staleTime;
if (this.prefetchTimestamp) {
this.prefetchTimestamp = (Date.now() + (this.prefetchTime * 1000)) / 1000;
}
}
maxStaleFailureJitter() {
const exponentialBackoffMillis = (1 << (this.refreshFaliure - 1));
return exponentialBackoffMillis > 10 ? exponentialBackoffMillis : 10;
}
jitterTime(time, jitterStart, jitterEnd) {
const jitterRange = jitterEnd - jitterStart;
const jitterAmount = Math.abs(Math.floor(Math.random() * jitterRange));
return time + jitterStart + jitterAmount;
}
async refreshSession() {
try {
const session = await this.refresher();
const now = Date.now() / 1000;
const oldSessionAvailable = this.staleTimestamp > now;
const oldSession = this.session;
this.expirationTimestamp = (0, time_1.parseUTC)(session.expiration) / 1000;
this.session = session;
this.refreshFaliure = 0;
this.refreshTimestamp();
// 过期时间大于15分钟不用管
if (this.staleTimestamp > now) {
return;
}
// 不足或等于15分钟但未过期下次会再次刷新
if (now < (this.staleTimestamp + this.staleTime)) {
this.expirationTimestamp = now + this.staleTime;
}
// 已过期看缓存缓存若大于15分钟返回缓存若小于15分钟则根据策略判断是立刻重试还是稍后重试
if (now > (this.staleTimestamp + this.staleTime)) {
if (oldSessionAvailable) {
this.session = oldSession;
this.expirationTimestamp = (0, time_1.parseUTC)(oldSession.expiration) / 1000;
this.refreshTimestamp();
return;
}
const waitUntilNextRefresh = 50 + (0, utils_1.getRandomInt)(20);
this.expirationTimestamp = now + waitUntilNextRefresh + this.staleTime;
}
}
catch (err) {
if (!this.session) {
throw err;
}
const now = Date.now() / 1000;
if (now < this.staleTimestamp) {
return;
}
this.refreshFaliure++;
this.expirationTimestamp = this.jitterTime(now, 1, this.maxStaleFailureJitter()) + this.staleTime;
}
}
async getSession() {
if (this.needUpdateCredential() || this.shouldPrefetchCredential()) {
await this.refreshSession();
this.refreshTimestamp();
}
return this.session;
}
needUpdateCredential() {
if (!this.session || !this.expirationTimestamp) {
return true;
}
return (Date.now() / 1000) >= this.staleTimestamp;
}
shouldPrefetchCredential() {
if (!this.prefetchTimestamp) {
return false;
}
return this.expirationTimestamp - (Date.now() / 1000) <= this.prefetchTime;
}
getProviderName() {
return 'session';
}
}
exports.SessionCredentialProvider = SessionCredentialProvider;
//# sourceMappingURL=session.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"session.js","sourceRoot":"","sources":["../../../src/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CAAC,cAAc,EAAE,CAAC;YAC5B,IAAI,CAAC,gBAAgB,EAAE,CAAC;SACzB;QACD,OAAO,IAAI,CAAC,OAAO,CAAC;IACtB,CAAC;IAED,oBAAoB;QAClB,IAAI,CAAC,IAAI,CAAC,OAAO,IAAI,CAAC,IAAI,CAAC,mBAAmB,EAAE;YAC9C,OAAO,IAAI,CAAC;SACb;QAED,OAAO,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,IAAI,IAAI,CAAC,cAAc,CAAC;IACpD,CAAC;IAED,wBAAwB;QACtB,IAAI,CAAC,IAAI,CAAC,iBAAiB,EAAE;YAC3B,OAAO,KAAK,CAAC;SACd;QAED,OAAO,IAAI,CAAC,mBAAmB,GAAG,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,IAAI,IAAI,CAAC,YAAY,CAAC;IAC7E,CAAC;IAED,eAAe;QACb,OAAO,SAAS,CAAC;IACnB,CAAC;CACJ;AApHD,8DAoHC"}

View File

@@ -0,0 +1,23 @@
import Credentials from '../credentials';
import CredentialsProvider from '../credentials_provider';
/**
* @internal
*/
export declare class StaticAKCredentialsProviderBuilder {
accessKeyId: string;
accessKeySecret: string;
withAccessKeyId(accessKeyId: string): StaticAKCredentialsProviderBuilder;
withAccessKeySecret(accessKeySecret: string): StaticAKCredentialsProviderBuilder;
build(): StaticAKCredentialsProvider;
}
/**
* @internal
*/
export default class StaticAKCredentialsProvider implements CredentialsProvider {
static builder(): StaticAKCredentialsProviderBuilder;
private readonly accessKeyId;
private readonly accessKeySecret;
constructor(builder: StaticAKCredentialsProviderBuilder);
getProviderName(): string;
getCredentials(): Promise<Credentials>;
}

View File

@@ -0,0 +1,61 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.StaticAKCredentialsProviderBuilder = void 0;
const credentials_1 = __importDefault(require("../credentials"));
/**
* @internal
*/
class StaticAKCredentialsProviderBuilder {
withAccessKeyId(accessKeyId) {
this.accessKeyId = accessKeyId;
return this;
}
withAccessKeySecret(accessKeySecret) {
this.accessKeySecret = accessKeySecret;
return this;
}
build() {
if (!this.accessKeyId) {
this.accessKeyId = process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'];
}
if (!this.accessKeyId) {
throw new Error('the access key id is empty');
}
if (!this.accessKeySecret) {
this.accessKeySecret = process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'];
}
if (!this.accessKeySecret) {
throw new Error('the access key secret is empty');
}
return new StaticAKCredentialsProvider(this);
}
}
exports.StaticAKCredentialsProviderBuilder = StaticAKCredentialsProviderBuilder;
/**
* @internal
*/
class StaticAKCredentialsProvider {
static builder() {
return new StaticAKCredentialsProviderBuilder();
}
constructor(builder) {
this.accessKeyId = builder.accessKeyId;
this.accessKeySecret = builder.accessKeySecret;
}
getProviderName() {
return 'static_ak';
}
async getCredentials() {
const credentials = credentials_1.default
.builder()
.withAccessKeyId(this.accessKeyId).withAccessKeySecret(this.accessKeySecret)
.withProviderName('static_ak')
.build();
return credentials;
}
}
exports.default = StaticAKCredentialsProvider;
//# sourceMappingURL=static_ak.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"static_ak.js","sourceRoot":"","sources":["../../../src/providers/static_ak.ts"],"names":[],"mappings":";;;;;;AACA,iEAAyC;AAGzC;;GAEG;AACH,MAAa,kCAAkC;IAItC,eAAe,CAAC,WAAmB;QACxC,IAAI,CAAC,WAAW,GAAG,WAAW,CAAC;QAC/B,OAAO,IAAI,CAAC;IACd,CAAC;IAEM,mBAAmB,CAAC,eAAuB;QAChD,IAAI,CAAC,eAAe,GAAG,eAAe,CAAC;QACvC,OAAO,IAAI,CAAC;IACd,CAAC;IAEM,KAAK;QACV,IAAI,CAAC,IAAI,CAAC,WAAW,EAAE;YACrB,IAAI,CAAC,WAAW,GAAG,OAAO,CAAC,GAAG,CAAC,6BAA6B,CAAC,CAAC;SAC/D;QAED,IAAI,CAAC,IAAI,CAAC,WAAW,EAAE;YACrB,MAAM,IAAI,KAAK,CAAC,4BAA4B,CAAC,CAAC;SAC/C;QAED,IAAI,CAAC,IAAI,CAAC,eAAe,EAAE;YACzB,IAAI,CAAC,eAAe,GAAG,OAAO,CAAC,GAAG,CAAC,iCAAiC,CAAC,CAAC;SACvE;QAED,IAAI,CAAC,IAAI,CAAC,eAAe,EAAE;YACzB,MAAM,IAAI,KAAK,CAAC,gCAAgC,CAAC,CAAC;SACnD;QAED,OAAO,IAAI,2BAA2B,CAAC,IAAI,CAAC,CAAC;IAC/C,CAAC;CACF;AAjCD,gFAiCC;AAED;;GAEG;AACH,MAAqB,2BAA2B;IAC9C,MAAM,CAAC,OAAO;QACZ,OAAO,IAAI,kCAAkC,EAAE,CAAC;IAClD,CAAC;IAKD,YAAmB,OAA4C;QAC7D,IAAI,CAAC,WAAW,GAAG,OAAO,CAAC,WAAW,CAAC;QACvC,IAAI,CAAC,eAAe,GAAG,OAAO,CAAC,eAAe,CAAC;IACjD,CAAC;IAED,eAAe;QACb,OAAO,WAAW,CAAC;IACrB,CAAC;IAED,KAAK,CAAC,cAAc;QAClB,MAAM,WAAW,GAAG,qBAAW;aAC5B,OAAO,EAAE;aACT,eAAe,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC,mBAAmB,CAAC,IAAI,CAAC,eAAe,CAAC;aAC3E,gBAAgB,CAAC,WAAW,CAAC;aAC7B,KAAK,EAAE,CAAC;QACX,OAAO,WAAW,CAAC;IACrB,CAAC;CACF;AAzBD,8CAyBC"}

View File

@@ -0,0 +1,26 @@
import Credentials from '../credentials';
import CredentialsProvider from '../credentials_provider';
/**
* @internal
*/
export declare class StaticSTSCredentialsProviderBuilder {
accessKeyId: string;
accessKeySecret: string;
securityToken: string;
withAccessKeyId(accessKeyId: string): StaticSTSCredentialsProviderBuilder;
withAccessKeySecret(accessKeySecret: string): StaticSTSCredentialsProviderBuilder;
withSecurityToken(securityToken: string): StaticSTSCredentialsProviderBuilder;
build(): StaticSTSCredentialsProvider;
}
/**
* @internal
*/
export default class StaticSTSCredentialsProvider implements CredentialsProvider {
static builder(): StaticSTSCredentialsProviderBuilder;
private readonly accessKeyId;
private readonly accessKeySecret;
private readonly securityToken;
constructor(builder: StaticSTSCredentialsProviderBuilder);
getProviderName(): string;
getCredentials(): Promise<Credentials>;
}

View File

@@ -0,0 +1,72 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.StaticSTSCredentialsProviderBuilder = void 0;
const credentials_1 = __importDefault(require("../credentials"));
/**
* @internal
*/
class StaticSTSCredentialsProviderBuilder {
withAccessKeyId(accessKeyId) {
this.accessKeyId = accessKeyId;
return this;
}
withAccessKeySecret(accessKeySecret) {
this.accessKeySecret = accessKeySecret;
return this;
}
withSecurityToken(securityToken) {
this.securityToken = securityToken;
return this;
}
build() {
if (!this.accessKeyId) {
this.accessKeyId = process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'];
}
if (!this.accessKeyId) {
throw new Error('the access key id is empty');
}
if (!this.accessKeySecret) {
this.accessKeySecret = process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'];
}
if (!this.accessKeySecret) {
throw new Error('the access key secret is empty');
}
if (!this.securityToken) {
this.securityToken = process.env['ALIBABA_CLOUD_SECURITY_TOKEN'];
}
if (!this.securityToken) {
throw new Error('the security token is empty');
}
return new StaticSTSCredentialsProvider(this);
}
}
exports.StaticSTSCredentialsProviderBuilder = StaticSTSCredentialsProviderBuilder;
/**
* @internal
*/
class StaticSTSCredentialsProvider {
static builder() {
return new StaticSTSCredentialsProviderBuilder();
}
constructor(builder) {
this.accessKeyId = builder.accessKeyId;
this.accessKeySecret = builder.accessKeySecret;
this.securityToken = builder.securityToken;
}
getProviderName() {
return 'static_sts';
}
async getCredentials() {
return credentials_1.default.builder()
.withAccessKeyId(this.accessKeyId)
.withAccessKeySecret(this.accessKeySecret)
.withSecurityToken(this.securityToken)
.withProviderName(this.getProviderName())
.build();
}
}
exports.default = StaticSTSCredentialsProvider;
//# sourceMappingURL=static_sts.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"static_sts.js","sourceRoot":"","sources":["../../../src/providers/static_sts.ts"],"names":[],"mappings":";;;;;;AACA,iEAAyC;AAGzC;;GAEG;AACH,MAAa,mCAAmC;IAKvC,eAAe,CAAC,WAAmB;QACxC,IAAI,CAAC,WAAW,GAAG,WAAW,CAAC;QAC/B,OAAO,IAAI,CAAC;IACd,CAAC;IAEM,mBAAmB,CAAC,eAAuB;QAChD,IAAI,CAAC,eAAe,GAAG,eAAe,CAAC;QACvC,OAAO,IAAI,CAAC;IACd,CAAC;IAEM,iBAAiB,CAAC,aAAqB;QAC5C,IAAI,CAAC,aAAa,GAAG,aAAa,CAAC;QACnC,OAAO,IAAI,CAAC;IACd,CAAC;IAEM,KAAK;QACV,IAAI,CAAC,IAAI,CAAC,WAAW,EAAE;YACrB,IAAI,CAAC,WAAW,GAAG,OAAO,CAAC,GAAG,CAAC,6BAA6B,CAAC,CAAC;SAC/D;QAED,IAAI,CAAC,IAAI,CAAC,WAAW,EAAE;YACrB,MAAM,IAAI,KAAK,CAAC,4BAA4B,CAAC,CAAC;SAC/C;QAED,IAAI,CAAC,IAAI,CAAC,eAAe,EAAE;YACzB,IAAI,CAAC,eAAe,GAAG,OAAO,CAAC,GAAG,CAAC,iCAAiC,CAAC,CAAC;SACvE;QAED,IAAI,CAAC,IAAI,CAAC,eAAe,EAAE;YACzB,MAAM,IAAI,KAAK,CAAC,gCAAgC,CAAC,CAAC;SACnD;QAED,IAAI,CAAC,IAAI,CAAC,aAAa,EAAE;YACvB,IAAI,CAAC,aAAa,GAAG,OAAO,CAAC,GAAG,CAAC,8BAA8B,CAAC,CAAC;SAClE;QAED,IAAI,CAAC,IAAI,CAAC,aAAa,EAAE;YACvB,MAAM,IAAI,KAAK,CAAC,6BAA6B,CAAC,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