feat: base shortcut code

This commit is contained in:
2025-01-18 21:54:26 +01:00
parent a820b29ea9
commit 3abe88c7a2
29 changed files with 5982 additions and 123 deletions

2
.env.example Normal file
View File

@@ -0,0 +1,2 @@
USER_KEY=""
ANTHROPIC_API_KEY=""

2
.env.test Normal file
View File

@@ -0,0 +1,2 @@
USER_KEY="test-key-123"
ANTHROPIC_API_KEY=""

23
.eslintrc.json Normal file
View File

@@ -0,0 +1,23 @@
{
"env": {
"node": true,
"es2021": true,
"jest": true
},
"extends": [
"next/core-web-vitals",
"eslint:recommended",
"plugin:@typescript-eslint/recommended",
"prettier"
],
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaVersion": "latest",
"sourceType": "module"
},
"plugins": ["@typescript-eslint"],
"rules": {
"@typescript-eslint/no-unused-vars": "error",
"@typescript-eslint/consistent-type-definitions": "error"
}
}

158
.gitignore vendored
View File

@@ -1,130 +1,44 @@
# Logs # See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
logs
*.log # dependencies
/node_modules
/.pnp
.pnp.js
.yarn/install-state.gz
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
# analyze
/analyze
# yarn
/.yarn
# misc
.DS_Store
*.pem
# debug
npm-debug.log* npm-debug.log*
yarn-debug.log* yarn-debug.log*
yarn-error.log* yarn-error.log*
lerna-debug.log*
.pnpm-debug.log*
# Diagnostic reports (https://nodejs.org/api/report.html) # local env files
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json .env*.local
# Runtime data # vercel
pids .vercel
*.pid
*.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover # typescript
lib-cov
# Coverage directory used by tools like istanbul
coverage
*.lcov
# nyc test coverage
.nyc_output
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# Snowpack dependency directory (https://snowpack.dev/)
web_modules/
# TypeScript cache
*.tsbuildinfo *.tsbuildinfo
next-env.d.ts
# Optional npm cache directory .env
.npm
# Optional eslint cache
.eslintcache
# Optional stylelint cache
.stylelintcache
# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variable files
.env
.env.development.local
.env.test.local
.env.production.local
.env.local
# parcel-bundler cache (https://parceljs.org/)
.cache
.parcel-cache
# Next.js build output
.next
out
# Nuxt.js build / generate output
.nuxt
dist
# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and not Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public
# vuepress build output
.vuepress/dist
# vuepress v2.x temp and cache directory
.temp
.cache
# Docusaurus cache and generated files
.docusaurus
# Serverless directories
.serverless/
# FuseBox cache
.fusebox/
# DynamoDB Local files
.dynamodb/
# TernJS port file
.tern-port
# Stores VSCode versions used for testing VSCode extensions
.vscode-test
# yarn v2
.yarn/cache
.yarn/unplugged
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.*

4
.husky/commit-msg Executable file
View File

@@ -0,0 +1,4 @@
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"
npx --no-install commitlint --edit $1

6
.husky/pre-commit Executable file
View File

@@ -0,0 +1,6 @@
yarn format
yarn audit
yarn lint-staged
yarn typecheck
yarn test
yarn build

9
.prettierrc Normal file
View File

@@ -0,0 +1,9 @@
{
"semi": true,
"trailingComma": "none",
"singleQuote": true,
"printWidth": 80,
"jsxSingleQuote": true,
"tabWidth": 2,
"arrowParens": "avoid"
}

5
.yarnrc.yml Normal file
View File

@@ -0,0 +1,5 @@
compressionLevel: mixed
enableGlobalCache: false
nodeLinker: node-modules

View File

@@ -1 +1,85 @@
# siri-shortcuts # Siri Shortcuts
A versatile backend service that extends Siri's capabilities through custom shortcuts, enabling AI-powered voice interactions and automated tasks. Built with TypeScript and Next.js, this project demonstrates how to create a bridge between Apple's Shortcuts app and custom backend logic.
## 🌟 Features
- **Custom Siri Commands**: Extend Siri's functionality through Apple Shortcuts integration
- **AI-Powered Responses**: Leverages Claude AI for intelligent, context-aware responses
- **Extensible Command System**: Easy-to-expand architecture for adding new commands
## 🛠️ Technology Stack
- **Framework**: Next.js 15
- **Language**: TypeScript
- **AI Integration**: Anthropic's Claude API
- **Testing**: Jest
- **Deployment**: Vercel
- **Code Quality**: ESLint, Prettier, Husky
## 🚀 Getting Started
1. **Install dependencies**
```bash
yarn install
```
2. **Set up environment variables**
```bash
cp .env.example .env
```
Fill in:
- `USER_KEY`: Your API authentication key
- `ANTHROPIC_API_KEY`: Your Anthropic API key for Claude AI
3. **Run development server**
```bash
yarn dev
```
4. **Run tests**
```bash
yarn test
```
## 📱 Setting Up Shortcuts
1. Create a new Shortcut in the iOS Shortcuts app
2. Add "Make HTTP Request" action
3. Configure the request:
- URL: Your deployed API endpoint
- Method: POST
- Headers: Content-Type: application/json
- Body:
```json
{
"command": "your_command",
"apiKey": "your_api_key",
"parameters": {}
}
```
## 🔍 Available Commands
- **ping**: Test the API connection
- **time**: Get the current time
- **anthropic**: Ask Claude AI a question
- Parameters: `{"question": "Your question here"}`
## 🔒 Security
- API key authentication required for all endpoints
- Secure headers configuration via Vercel
- Rate limiting and request validation
- HTTPS-only communication
## 🔮 Future Enhancements
- [ ] Add more AI-powered commands
- [ ] Implement user preferences and data storage
- [ ] Integrate with more external services

View File

@@ -0,0 +1,65 @@
import { POST } from './route';
describe('Shortcuts API Route', () => {
const originalEnv = process.env;
beforeEach(() => {
process.env = { ...originalEnv };
process.env.USER_KEY = 'test-key-123';
});
afterEach(() => {
process.env = originalEnv;
});
it('should handle valid ping request', async () => {
const request = new Request('http://localhost:3000/api/shortcuts', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
command: 'ping',
apiKey: 'test-key-123'
})
});
const response = await POST(request);
const data = await response.json();
expect(response.status).toBe(200);
expect(data.success).toBe(true);
expect(data.message).toContain('operational');
});
it('should reject invalid API key', async () => {
const request = new Request('http://localhost:3000/api/shortcuts', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
command: 'ping',
apiKey: 'wrong-key'
})
});
const response = await POST(request);
expect(response.status).toBe(401);
});
it('should handle invalid request format', async () => {
const request = new Request('http://localhost:3000/api/shortcuts', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
command: 'ping'
})
});
const response = await POST(request);
expect(response.status).toBe(400);
});
});

50
app/api/shortcut/route.ts Normal file
View File

@@ -0,0 +1,50 @@
import { NextResponse } from 'next/server';
import { ShortcutsHandler } from '@utils/handler';
import { RequestSchema } from '@utils/types';
export async function POST(req: Request) {
try {
const body = await req.json();
const result = RequestSchema.safeParse(body);
if (!result.success) {
return NextResponse.json(
{
success: false,
message: 'Invalid request format.',
errors: result.error.errors
},
{ status: 400 }
);
}
const shortcutsHandler = new ShortcutsHandler();
const isValid = shortcutsHandler.validateRequest(result.data);
if (!isValid) {
return NextResponse.json(
{
success: false,
message: 'Unauthorized.'
},
{ status: 401 }
);
}
const response = await shortcutsHandler.processCommand(
result.data.command,
result.data.parameters
);
return NextResponse.json(response);
} catch (error) {
console.error('Error processing shortcuts request:', error);
return NextResponse.json(
{
success: false,
message: 'An error occurred while processing your request.'
},
{ status: 500 }
);
}
}

3
commitlint.config.ts Normal file
View File

@@ -0,0 +1,3 @@
module.exports = {
extends: ['@commitlint/config-conventional']
};

15
jest.config.ts Normal file
View File

@@ -0,0 +1,15 @@
/** @type {import('jest').Config} */
const config = {
preset: 'ts-jest',
testEnvironment: 'node',
moduleNameMapper: {
'^@api/(.*)$': '<rootDir>/app/api/$1',
'^@utils/(.*)$': '<rootDir>/utils/$1'
},
testMatch: ['**/__tests__/**/*.test.ts', '**/*.test.ts'],
clearMocks: true,
collectCoverage: true,
coverageDirectory: 'coverage'
};
module.exports = config;

4
next.config.js Normal file
View File

@@ -0,0 +1,4 @@
/** @type {import('next').NextConfig} */
const nextConfig = {};
module.exports = nextConfig;

56
package.json Normal file
View File

@@ -0,0 +1,56 @@
{
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint",
"format": "prettier --config .prettierrc '**/*.{js,jsx,ts,tsx,json,css,scss,md}' --write",
"typecheck": "tsc --noEmit",
"test": "jest",
"test:watch": "jest --watch",
"test:coverage": "jest --coverage",
"prepare": "husky install",
"analyze": "BUNDLE_ANALYZE=true next build",
"audit": "audit-ci",
"vercel:link": "vercel link",
"vercel:env": "vercel env pull .env"
},
"dependencies": {
"@anthropic-ai/sdk": "^0.33.1",
"axios": "^1.7.9",
"next": "^15.1.3",
"react": "^19.0.0",
"react-dom": "^19.0.0",
"zod": "^3.24.1"
},
"devDependencies": {
"@commitlint/cli": "^19.6.1",
"@commitlint/config-conventional": "^19.6.0",
"@types/jest": "^29.5.14",
"@types/node": "^22.10.2",
"@types/react": "^19.0.2",
"@types/react-dom": "^19.0.2",
"@typescript-eslint/eslint-plugin": "^8.18.2",
"@typescript-eslint/parser": "^8.18.2",
"autoprefixer": "^10.4.20",
"dotenv": "^16.4.7",
"eslint": "^8.56.0",
"eslint-config-next": "^15.1.3",
"eslint-config-prettier": "^9.1.0",
"husky": "^9.1.7",
"jest": "^29.7.0",
"lint-staged": "^15.3.0",
"prettier": "^3.4.2",
"ts-jest": "^29.2.5",
"ts-node": "^10.9.2",
"typescript": "^5.7.2"
},
"lint-staged": {
"*.{ts,tsx}": [
"eslint --quiet --fix"
],
"*.{json,ts,tsx}": [
"prettier --write --ignore-unknown"
]
}
}

BIN
public/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

28
tsconfig.json Normal file
View File

@@ -0,0 +1,28 @@
{
"compilerOptions": {
"target": "ES5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@api/*": ["./app/api/*"],
"@utils/*": ["./utils/*"]
}
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"exclude": ["node_modules", ".yarn", ".next", ".vercel", ".vscode"]
}

25
utils/anthropicClient.ts Normal file
View File

@@ -0,0 +1,25 @@
import Anthropic from '@anthropic-ai/sdk';
export async function getMessage(text: string) {
const anthropic = new Anthropic({
apiKey: process.env.ANTHROPIC_API_KEY
});
console.info('Anthropic request with text: ', text);
const response = await anthropic.messages.create({
model: 'claude-3-5-sonnet-20241022',
max_tokens: 2048,
messages: [{ role: 'user', content: text }]
});
console.info('Anthropic response: ', response);
try {
const data = response.content as [{ type: string; text: string }];
return data[0].text;
} catch (error) {
throw new Error(`Anthropic client error: ${JSON.stringify(error)}.`);
}
}

View File

@@ -0,0 +1,32 @@
import { getMessage } from '@utils/anthropicClient';
import { ShortcutsResponse } from '../types';
export async function anthropicCommand(
parameters: Record<string, string> | undefined
): Promise<ShortcutsResponse> {
try {
if (!parameters || !parameters['question']) {
return {
success: false,
message: 'Sorry. Need to provide a question.'
};
}
const response = await getMessage(
'I want to know ' +
parameters['question'] +
'. Structure the response in a manner suitable for spoken communication.'
);
return {
success: true,
message: response
};
} catch (error) {
console.error(error);
return {
success: false,
message: 'Sorry. There was a problem with Anthropic.'
};
}
}

View File

@@ -0,0 +1,11 @@
import { pingCommand } from './ping';
describe('Ping Command', () => {
it('should return success response', async () => {
const response = await pingCommand();
expect(response.success).toBe(true);
expect(response.message).toBe('The system is operational.');
expect(response.data).toHaveProperty('timestamp');
});
});

11
utils/commands/ping.ts Normal file
View File

@@ -0,0 +1,11 @@
import { ShortcutsResponse } from '../types';
export async function pingCommand(): Promise<ShortcutsResponse> {
return {
success: true,
message: 'The system is operational.',
data: {
timestamp: new Date().toISOString()
}
};
}

View File

@@ -0,0 +1,12 @@
import { timeCommand } from './time';
describe('Time Command', () => {
it('should return current time', async () => {
const response = await timeCommand();
expect(response.success).toBe(true);
expect(response.message).toMatch(/It's currently \d{1,2}:\d{2} [AP]M/);
expect(response.data).toHaveProperty('timestamp');
expect(response.data).toHaveProperty('formattedTime');
});
});

19
utils/commands/time.ts Normal file
View File

@@ -0,0 +1,19 @@
import { ShortcutsResponse } from '../types';
export async function timeCommand(): Promise<ShortcutsResponse> {
const now = new Date();
const timeString = now.toLocaleTimeString('en-US', {
hour: 'numeric',
minute: 'numeric',
hour12: true
});
return {
success: true,
message: `It's currently ${timeString}`,
data: {
timestamp: now.toISOString(),
formattedTime: timeString
}
};
}

54
utils/handler.test.ts Normal file
View File

@@ -0,0 +1,54 @@
import { ShortcutsHandler } from './handler';
describe('ShortcutsHandler', () => {
let handler: ShortcutsHandler;
const originalEnv = process.env;
beforeEach(() => {
process.env = { ...originalEnv };
process.env.USER_KEY = 'test-key-123';
handler = new ShortcutsHandler();
});
afterEach(() => {
process.env = originalEnv;
});
describe('validateRequest', () => {
it('should validate correct API key', () => {
const isValid = handler.validateRequest({
command: 'test',
apiKey: 'test-key-123'
});
expect(isValid).toBe(true);
});
it('should reject invalid API key', () => {
const isValid = handler.validateRequest({
command: 'test',
apiKey: 'wrong-key'
});
expect(isValid).toBe(false);
});
});
describe('processCommand', () => {
it('should handle ping command', async () => {
const response = await handler.processCommand('ping');
expect(response.success).toBe(true);
expect(response.message).toContain('operational');
});
it('should handle time command', async () => {
const response = await handler.processCommand('time');
expect(response.success).toBe(true);
expect(response.message).toMatch(/currently/);
});
it('should handle unknown command', async () => {
const response = await handler.processCommand('unknown');
expect(response.success).toBe(false);
expect(response.message).toContain('Unknown command');
});
});
});

45
utils/handler.ts Normal file
View File

@@ -0,0 +1,45 @@
import { ShortcutsRequest, ShortcutsResponse } from './types';
import { CommandRegistry } from './registry';
export class ShortcutsHandler {
private registry: CommandRegistry;
constructor() {
this.registry = new CommandRegistry();
}
validateRequest(req: ShortcutsRequest): boolean {
try {
const isValidUser = req.apiKey == process.env.USER_KEY;
return !!isValidUser;
} catch (error) {
console.error('Error validating request:', error);
return false;
}
}
async processCommand(
command: string,
parameters?: Record<string, string>
): Promise<ShortcutsResponse> {
const handler = this.registry.getCommand(command);
if (!handler) {
return {
success: false,
message: `Unknown command: ${command}.`
};
}
try {
return await handler(parameters);
} catch (error) {
console.error(`Error processing command ${command}:`, error);
return {
success: false,
message: 'An error occurred while processing your command.'
};
}
}
}

31
utils/registry.ts Normal file
View File

@@ -0,0 +1,31 @@
import { ShortcutsResponse } from './types';
import { pingCommand } from './commands/ping';
import { timeCommand } from './commands/time';
import { anthropicCommand } from './commands/anthropic';
type CommandHandler = (
parameters?: Record<string, string>
) => Promise<ShortcutsResponse>;
export class CommandRegistry {
private commands: Map<string, CommandHandler>;
constructor() {
this.commands = new Map();
this.registerDefaultCommands();
}
private registerDefaultCommands() {
this.register('ping', pingCommand);
this.register('time', timeCommand);
this.register('anthropic', anthropicCommand);
}
register(command: string, handler: CommandHandler) {
this.commands.set(command.toLowerCase(), handler);
}
getCommand(command: string): CommandHandler | undefined {
return this.commands.get(command.toLowerCase());
}
}

19
utils/types.ts Normal file
View File

@@ -0,0 +1,19 @@
import { z } from 'zod';
export const RequestSchema = z.object({
command: z.string(),
parameters: z.record(z.string()).optional(),
apiKey: z.string()
});
export type ShortcutsRequest = z.infer<typeof RequestSchema>;
export interface ShortcutsResponse {
success: boolean;
message: string;
data?: unknown;
action?: {
type: 'notification' | 'openUrl' | 'runShortcut' | 'wait';
payload: unknown;
};
}

43
vercel.json Normal file
View File

@@ -0,0 +1,43 @@
{
"functions": {
"app/api/**/*": {
"maxDuration": 30
}
},
"headers": [
{
"source": "/api/(.*)",
"headers": [
{
"key": "Access-Control-Allow-Methods",
"value": "GET, POST, OPTIONS"
},
{
"key": "Access-Control-Allow-Headers",
"value": "Content-Type, Accept"
},
{
"key": "Strict-Transport-Security",
"value": "max-age=63072000; includeSubDomains; preload"
},
{
"key": "Content-Security-Policy",
"value": "default-src 'none'"
},
{
"key": "X-Content-Type-Options",
"value": "nosniff"
},
{
"key": "X-Frame-Options",
"value": "DENY"
},
{ "key": "Referrer-Policy", "value": "same-origin" },
{
"key": "X-XSS-Protection",
"value": "1; mode=block"
}
]
}
]
}

5287
yarn.lock Normal file

File diff suppressed because it is too large Load Diff