@snowcone-app/mockup-resolver 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json ADDED
@@ -0,0 +1,44 @@
1
+ {
2
+ "name": "@snowcone-app/mockup-resolver",
3
+ "version": "1.0.0",
4
+ "description": "URL signing and verification Cloudflare Worker",
5
+ "main": "dist/index.js",
6
+ "author": "",
7
+ "license": "ISC",
8
+ "dependencies": {
9
+ "@snowcone-app/mockup-url": "0.1.0"
10
+ },
11
+ "devDependencies": {
12
+ "@cloudflare/workers-types": "^4.20250303.0",
13
+ "@types/jest": "^29.5.12",
14
+ "@types/node": "^20.12.6",
15
+ "@types/node-fetch": "^2.6.12",
16
+ "node-fetch": "^3.3.2",
17
+ "tsx": "^4.19.3",
18
+ "typescript": "^5.6.2",
19
+ "vite": "^5.0.0",
20
+ "vitest": "^2.0.0",
21
+ "wrangler": "^3.37.0"
22
+ },
23
+ "scripts": {
24
+ "dev": "wrangler dev src/index.ts",
25
+ "dev:remote": "wrangler dev",
26
+ "build": "tsc",
27
+ "deploy": "wrangler deploy src/index.ts",
28
+ "test": "vitest run --exclude '**/integration/**'",
29
+ "test:watch": "vitest",
30
+ "test:integration": "vitest run integration/",
31
+ "test:integration:watch": "vitest integration/",
32
+ "clean": "rm -rf dist node_modules .wrangler",
33
+ "typecheck": "tsc --noEmit",
34
+ "seed:local": "tsx scripts/seed-local-kv.ts",
35
+ "seed:prod": "node scripts/seed-prod-kv.js",
36
+ "check": "tsx scripts/check-service.ts",
37
+ "build:worker": "node scripts/build-worker.js",
38
+ "deploy:worker": "pnpm build:worker && wrangler deploy --env development",
39
+ "setup:env": "./scripts/setup-env.sh",
40
+ "setup:env:dev": "wrangler secret put URL_SIGNING_SECRET --env development",
41
+ "setup:env:prod": "wrangler secret put URL_SIGNING_SECRET",
42
+ "set:secret": "wrangler secret put URL_SIGNING_SECRET --name mockup-resolver"
43
+ }
44
+ }
@@ -0,0 +1,101 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Mockup Resolver Worker Build Script
4
+ *
5
+ * This script builds the Mockup Resolver Worker by:
6
+ * 1. Creating the worker file
7
+ * 2. Adding a generation header
8
+ * 3. Creating the wrangler configuration
9
+ */
10
+
11
+ const fs = require('fs')
12
+ const path = require('path')
13
+
14
+ // Source and destination paths
15
+ const SOURCE_FILE = path.resolve(__dirname, '../worker.js')
16
+ const DEST_FILE = path.resolve(__dirname, '../dist/worker.js')
17
+ const WRANGLER_CONFIG = path.resolve(__dirname, '../wrangler.toml')
18
+
19
+ // Ensure destination directory exists
20
+ const destDir = path.dirname(DEST_FILE)
21
+ if (!fs.existsSync(destDir)) {
22
+ fs.mkdirSync(destDir, { recursive: true })
23
+ console.log(`Created directory: ${destDir}`)
24
+ }
25
+
26
+ // Read source file
27
+ const sourceCode = fs.readFileSync(SOURCE_FILE, 'utf8')
28
+
29
+ // Add generation header
30
+ const generatedCode = `/**
31
+ * GENERATED FILE - DO NOT EDIT DIRECTLY
32
+ * Generated from worker.js
33
+ * Generated at: ${new Date().toISOString()}
34
+ */
35
+
36
+ ${sourceCode}`
37
+
38
+ // Write worker file to destination
39
+ fs.writeFileSync(DEST_FILE, generatedCode)
40
+ console.log(`โœ… Mockup Resolver Worker built at: ${DEST_FILE}`)
41
+
42
+ // Read existing wrangler.toml to preserve KV namespaces and other settings
43
+ const existingConfig = fs.existsSync(WRANGLER_CONFIG)
44
+ ? fs.readFileSync(WRANGLER_CONFIG, 'utf8')
45
+ : ''
46
+
47
+ // Only update wrangler.toml if it doesn't exist
48
+ if (!fs.existsSync(WRANGLER_CONFIG)) {
49
+ const wranglerConfig = `name = "mockup-resolver"
50
+ main = "dist/worker.js"
51
+ compatibility_date = "2024-03-01"
52
+
53
+ # Custom domain route configuration
54
+ workers_dev = false
55
+ routes = [
56
+ { pattern = "api.snowcone.app/v1/url-signer*", zone_name = "snowcone.app" }
57
+ ]
58
+
59
+ # KV namespace for all environments
60
+ [[kv_namespaces]]
61
+ binding = "ACCOUNTS"
62
+ id = "de3d0db77ca34aeaa95e808e574d2f04"
63
+
64
+ # Enable observability logs
65
+ [observability.logs]
66
+ enabled = true
67
+
68
+ # Default variables for all environments
69
+ [vars]
70
+ TTL_DEFAULT = "3600" # Default expiration time in seconds
71
+ LOG_LEVEL = "info" # Logging level
72
+
73
+ # Production environment
74
+ [env.production]
75
+ vars = { TTL_DEFAULT = "86400", LOG_LEVEL = "info" }
76
+
77
+ # Production KV namespaces
78
+ [[env.production.kv_namespaces]]
79
+ binding = "ACCOUNTS"
80
+ id = "de3d0db77ca34aeaa95e808e574d2f04"
81
+
82
+ # Development environment
83
+ [env.development]
84
+ vars = { TTL_DEFAULT = "3600", LOG_LEVEL = "debug" }
85
+
86
+ # Development KV namespaces
87
+ [[env.development.kv_namespaces]]
88
+ binding = "ACCOUNTS"
89
+ id = "de3d0db77ca34aeaa95e808e574d2f04"
90
+
91
+ # Development server config
92
+ [dev]
93
+ port = 8102
94
+ local_protocol = "http"
95
+ `
96
+
97
+ fs.writeFileSync(WRANGLER_CONFIG, wranglerConfig)
98
+ console.log(`โœ… Created Wrangler configuration: ${WRANGLER_CONFIG}`)
99
+ }
100
+
101
+ console.log('Mockup Resolver Worker build completed successfully!')
@@ -0,0 +1,69 @@
1
+ import fetch from 'node-fetch'
2
+
3
+ const BASE_URL = 'http://localhost:8102'
4
+ const TEST_API_KEY = 'test-api-key-1' // Use one of our seeded API keys
5
+ const TEST_URL = 'https://example.com/image.jpg'
6
+
7
+ async function checkService() {
8
+ console.log('๐Ÿ” Checking Mockup Resolver Service...')
9
+
10
+ try {
11
+ // First try a root request (expected to fail with 401, but shows service is running)
12
+ try {
13
+ const rootResponse = await fetch(BASE_URL)
14
+ console.log(`โ„น๏ธ Root endpoint response status: ${rootResponse.status}`)
15
+
16
+ if (rootResponse.status === 401) {
17
+ console.log('โœ… Service is running and correctly requiring authentication!')
18
+ }
19
+ } catch (error) {
20
+ console.error('โŒ Service is not running:')
21
+ console.error(` ${error instanceof Error ? error.message : String(error)}`)
22
+ return false
23
+ }
24
+
25
+ // Now try a signing request with proper authentication
26
+ console.log('\n๐Ÿ“ Testing URL signing with API key authentication...')
27
+ const signResponse = await fetch(`${BASE_URL}/sign?url=${encodeURIComponent(TEST_URL)}`, {
28
+ headers: {
29
+ 'x-api-key': TEST_API_KEY,
30
+ },
31
+ })
32
+
33
+ if (signResponse.ok) {
34
+ const data = await signResponse.json()
35
+ console.log('โœ… Successfully signed URL!')
36
+ console.log(`๐Ÿ“‹ Response:`, data)
37
+ return true
38
+ } else {
39
+ console.log(`โŒ Signing request failed with status: ${signResponse.status}`)
40
+ const text = await signResponse.text()
41
+ console.log(`Response: ${text}`)
42
+
43
+ // Check if this is a KV access issue
44
+ if (signResponse.status === 401 && text.includes('Invalid API key')) {
45
+ console.log('\nโš ๏ธ KV data may not be properly seeded.')
46
+ console.log(" Run 'pnpm run seed:local' to seed the KV store with test data.")
47
+ }
48
+
49
+ return false
50
+ }
51
+ } catch (error) {
52
+ console.error('โŒ Service check failed:')
53
+ console.error(` ${error instanceof Error ? error.message : String(error)}`)
54
+
55
+ console.log('\nโš ๏ธ Common solutions:')
56
+ console.log('1. Make sure the server is running with: pnpm run dev:local')
57
+ console.log('2. Check if something else is using port 8102')
58
+ console.log('3. Verify your wrangler.toml configuration is correct')
59
+ console.log('4. Ensure the KV namespaces are properly seeded with: pnpm run seed:local')
60
+
61
+ return false
62
+ }
63
+ }
64
+
65
+ checkService().then((success) => {
66
+ if (!success) {
67
+ process.exit(1)
68
+ }
69
+ })
@@ -0,0 +1,180 @@
1
+ import { exec } from "child_process";
2
+ import { promisify } from "util";
3
+ import * as fs from "fs";
4
+ import * as path from "path";
5
+
6
+ const execAsync = promisify(exec);
7
+
8
+ /**
9
+ * This script seeds the local KV store with test data for development
10
+ */
11
+
12
+ // Define accounts with their API keys and clientIds
13
+ const accounts = [
14
+ {
15
+ accountId: "account123",
16
+ apiKeys: {
17
+ "dev-api-key": { rateLimit: 1000 },
18
+ "dev-api-key-2": { rateLimit: 1000 },
19
+ "dev-api-key-readonly": { rateLimit: 500 },
20
+ "test-api-key-1": { rateLimit: 2000 },
21
+ "test-api-key-1-readonly": { rateLimit: 500 },
22
+ },
23
+ clientIds: {
24
+ dev_client: {
25
+ rateLimit: 100,
26
+ },
27
+ client_all_origins: {
28
+ rateLimit: 50,
29
+ },
30
+ },
31
+ },
32
+ {
33
+ accountId: "account456",
34
+ apiKeys: {
35
+ "test-api-key-2": { rateLimit: 2000 },
36
+ "test-api-key-2-readonly": { rateLimit: 500 },
37
+ "sdk-test-key-1": { rateLimit: 1000 },
38
+ "sdk-test-key-2": { rateLimit: 1000 },
39
+ },
40
+ clientIds: {
41
+ client_1: {
42
+ rateLimit: 200,
43
+ },
44
+ client_2: {
45
+ rateLimit: 300,
46
+ },
47
+ },
48
+ },
49
+ ];
50
+
51
+ async function seedData() {
52
+ console.log("Seeding KV store...");
53
+
54
+ try {
55
+ // Use wrangler's CLI to put the accounts into the KV namespace
56
+ console.log("Reading wrangler.toml to find namespace ID...");
57
+
58
+ // Extract the namespace ID from wrangler.toml
59
+ const wranglerConfig = fs.readFileSync(
60
+ path.join(__dirname, "../wrangler.toml"),
61
+ "utf-8"
62
+ );
63
+ const namespaceMatch = wranglerConfig.match(/id\s*=\s*"([^"]+)"/);
64
+
65
+ if (!namespaceMatch) {
66
+ throw new Error("Could not find namespace ID in wrangler.toml");
67
+ }
68
+
69
+ const namespaceId = namespaceMatch[1];
70
+ console.log(`Found namespace ID: ${namespaceId}`);
71
+
72
+ // Seed account data using wrangler CLI
73
+ for (const account of accounts) {
74
+ console.log(`\nSeeding account: ${account.accountId}`);
75
+
76
+ try {
77
+ // Create a temporary JSON file for this account
78
+ const tempFilePath = path.join(
79
+ __dirname,
80
+ `../temp_${account.accountId}.json`
81
+ );
82
+ fs.writeFileSync(tempFilePath, JSON.stringify(account));
83
+
84
+ // Use wrangler to put the key/value into the KV namespace
85
+ const command = `npx wrangler kv key put --namespace-id=${namespaceId} "${account.accountId}" --path=${tempFilePath}`;
86
+ console.log(`Running command: ${command}`);
87
+
88
+ const { stdout, stderr } = await execAsync(command);
89
+ console.log(stdout);
90
+
91
+ if (stderr) {
92
+ console.error(`Error output: ${stderr}`);
93
+ }
94
+
95
+ // Clean up the temporary file
96
+ fs.unlinkSync(tempFilePath);
97
+ console.log(`โœ… Seeded account ${account.accountId}`);
98
+ } catch (err) {
99
+ console.error(`Failed to seed account ${account.accountId}: ${err}`);
100
+ }
101
+ }
102
+ } catch (error) {
103
+ console.error("Failed to seed data:", error);
104
+
105
+ // Fallback to local file method if wrangler command fails
106
+ console.log("\nFalling back to local file method...");
107
+ await seedLocalFiles();
108
+ }
109
+
110
+ console.log("\nโœ… KV data seeded successfully!");
111
+
112
+ console.log("\nTest with:");
113
+ console.log(
114
+ '1. API key auth: curl -H "x-api-key: test-api-key-1" "http://localhost:8102/sign?url=https://example.com/image.jpg&accountId=account123"'
115
+ );
116
+ }
117
+
118
+ // Fallback method that creates local files directly
119
+ async function seedLocalFiles() {
120
+ // Create both potential KV directories - the original ACCOUNTS and the local_accounts paths
121
+ const kvDirs = [
122
+ path.join(__dirname, "../.wrangler/state/kv/ACCOUNTS"),
123
+ path.join(__dirname, "../.wrangler/state/kv/local_accounts"),
124
+ path.join(
125
+ __dirname,
126
+ "../.wrangler/state/kv/de3d0db77ca34aeaa95e808e574d2f04"
127
+ ),
128
+ ];
129
+
130
+ for (const kvDir of kvDirs) {
131
+ try {
132
+ await fs.promises.mkdir(kvDir, { recursive: true });
133
+ console.log(`Created KV directory: ${kvDir}`);
134
+ } catch (err) {
135
+ console.log(`KV directory already exists or error creating: ${kvDir}`);
136
+ }
137
+ }
138
+
139
+ // Seed account data
140
+ for (const account of accounts) {
141
+ console.log(`\nSeeding account: ${account.accountId}`);
142
+
143
+ // For each account, seed all directories
144
+ for (const kvDir of kvDirs) {
145
+ try {
146
+ // Store in Miniflare KV format (metadata file + value file)
147
+ const accountId = account.accountId;
148
+
149
+ // Create a unique filename for the value
150
+ const valueFilename = `${accountId}_value_${Date.now()}`;
151
+ const valueFilePath = path.join(kvDir, valueFilename);
152
+
153
+ // Write the value file
154
+ await fs.promises.writeFile(valueFilePath, JSON.stringify(account));
155
+
156
+ // Create metadata file with the key name
157
+ const metadataFilePath = path.join(kvDir, accountId);
158
+ const metadata = {
159
+ key: accountId,
160
+ value: valueFilename,
161
+ };
162
+
163
+ // Write the metadata file
164
+ await fs.promises.writeFile(metadataFilePath, JSON.stringify(metadata));
165
+
166
+ console.log(`โœ… Seeded account ${accountId} in ${kvDir}`);
167
+ } catch (err) {
168
+ console.error(
169
+ `Failed to write account ${account.accountId} to ${kvDir}: ${err}`
170
+ );
171
+ }
172
+ }
173
+ }
174
+ }
175
+
176
+ // Run the seeding
177
+ seedData().catch((error) => {
178
+ console.error("Failed to seed data:", error);
179
+ process.exit(1);
180
+ });
@@ -0,0 +1,97 @@
1
+ #!/usr/bin/env node
2
+ const fs = require('fs');
3
+ const path = require('path');
4
+ const { exec } = require('child_process');
5
+ const { promisify } = require('util');
6
+
7
+ const execAsync = promisify(exec);
8
+
9
+ /**
10
+ * This script seeds the production KV store with account data
11
+ */
12
+
13
+ // Define accounts with their API keys and clientIds
14
+ const accounts = [
15
+ {
16
+ accountId: 'account123',
17
+ apiKeys: {
18
+ 'dev-api-key': { rateLimit: 1000 },
19
+ 'dev-api-key-2': { rateLimit: 1000 },
20
+ 'dev-api-key-readonly': { rateLimit: 500 },
21
+ 'test-api-key-1': { rateLimit: 2000 },
22
+ 'test-api-key-1-readonly': { rateLimit: 500 },
23
+ },
24
+ clientIds: {
25
+ dev_client: {
26
+ rateLimit: 100,
27
+ },
28
+ client_all_origins: {
29
+ rateLimit: 50,
30
+ },
31
+ },
32
+ },
33
+ {
34
+ accountId: 'account456',
35
+ apiKeys: {
36
+ 'test-api-key-2': { rateLimit: 2000 },
37
+ 'test-api-key-2-readonly': { rateLimit: 500 },
38
+ 'sdk-test-key-1': { rateLimit: 1000 },
39
+ 'sdk-test-key-2': { rateLimit: 1000 },
40
+ },
41
+ clientIds: {
42
+ client_1: {
43
+ rateLimit: 200,
44
+ },
45
+ client_2: {
46
+ rateLimit: 300,
47
+ },
48
+ },
49
+ },
50
+ ]
51
+
52
+ async function seedProductionData() {
53
+ console.log('๐ŸŒฑ Seeding production KV store...')
54
+
55
+ try {
56
+ // Create bulk upload data - stringify the value field
57
+ const bulkData = accounts.map(account => ({
58
+ key: account.accountId,
59
+ value: JSON.stringify(account) // Convert the value to a string
60
+ }))
61
+
62
+ // Write to temporary file
63
+ const tempFile = path.join(__dirname, '..', 'temp-bulk-upload.json')
64
+ fs.writeFileSync(tempFile, JSON.stringify(bulkData, null, 2))
65
+
66
+ console.log('๐Ÿ“ Created bulk upload file')
67
+
68
+ // Upload to production KV store
69
+ const { stdout, stderr } = await execAsync(
70
+ 'npx wrangler kv bulk put temp-bulk-upload.json --binding=ACCOUNTS --env=production --remote'
71
+ )
72
+
73
+ console.log('\nโœจ Upload output:')
74
+ if (stdout) console.log(stdout)
75
+ if (stderr) console.error(stderr)
76
+
77
+ // Clean up temp file
78
+ fs.unlinkSync(tempFile)
79
+ console.log('๐Ÿงน Cleaned up temporary file')
80
+
81
+ // Verify the upload
82
+ console.log('\n๐Ÿ” Verifying upload...')
83
+ const { stdout: listStdout } = await execAsync(
84
+ 'npx wrangler kv key list --binding=ACCOUNTS --env=production --remote'
85
+ )
86
+ console.log('๐Ÿ“‹ Current keys in production:')
87
+ console.log(listStdout)
88
+
89
+ console.log('\nโœ… Production KV store seeded successfully!')
90
+ } catch (error) {
91
+ console.error('โŒ Failed to seed production data:', error)
92
+ process.exit(1)
93
+ }
94
+ }
95
+
96
+ // Run the seeding
97
+ seedProductionData()
@@ -0,0 +1,62 @@
1
+ #!/bin/bash
2
+ # Mockup Resolver Environment Setup Script
3
+ #
4
+ # This script sets up the environment variables for the mockup resolver worker
5
+ # in Cloudflare Workers.
6
+
7
+ set -e
8
+
9
+ # Output formatting
10
+ GREEN='\033[0;32m'
11
+ YELLOW='\033[1;33m'
12
+ RED='\033[0;31m'
13
+ NC='\033[0m' # No Color
14
+
15
+ # Check if wrangler is installed
16
+ if ! command -v wrangler &> /dev/null; then
17
+ echo -e "${RED}Error: wrangler is not installed${NC}"
18
+ echo "Please install wrangler with: npm install -g wrangler"
19
+ exit 1
20
+ fi
21
+
22
+ # Load .env file if it exists
23
+ if [ -f ".env" ]; then
24
+ echo -e "${YELLOW}Loading environment variables from .env file...${NC}"
25
+ export $(grep -v '^#' .env | xargs)
26
+ fi
27
+
28
+ # Check for required variables
29
+ if [ -z "$SIGNING_SECRET" ]; then
30
+ echo -e "${YELLOW}SIGNING_SECRET not found in environment. Generating a random one...${NC}"
31
+ SIGNING_SECRET=$(openssl rand -base64 32)
32
+ echo -e "${GREEN}Generated random signing secret. You may want to save this for future use.${NC}"
33
+ fi
34
+
35
+ # Set environment for development
36
+ echo -e "${YELLOW}Setting up development environment...${NC}"
37
+ wrangler secret put SIGNING_SECRET --env development <<< "$SIGNING_SECRET"
38
+
39
+ # Ask if production environment should be set up
40
+ read -p "Do you want to set up the production environment too? (y/n) " -n 1 -r
41
+ echo
42
+ if [[ $REPLY =~ ^[Yy]$ ]]; then
43
+ echo -e "${YELLOW}Setting up production environment...${NC}"
44
+
45
+ # For production, we should ask for confirmation when using the same secret
46
+ read -p "Use the same signing secret for production? (y/n) " -n 1 -r
47
+ echo
48
+ if [[ ! $REPLY =~ ^[Yy]$ ]]; then
49
+ echo -e "${YELLOW}Please enter the production signing secret:${NC}"
50
+ read -s PROD_SIGNING_SECRET
51
+ echo
52
+ else
53
+ PROD_SIGNING_SECRET="$SIGNING_SECRET"
54
+ fi
55
+
56
+ wrangler secret put SIGNING_SECRET --env production <<< "$PROD_SIGNING_SECRET"
57
+
58
+ echo -e "${GREEN}Production environment set up successfully!${NC}"
59
+ fi
60
+
61
+ echo -e "${GREEN}Environment setup completed successfully!${NC}"
62
+ echo -e "You can now deploy your worker with: wrangler publish --env [development|production]"
File without changes