Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 70 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
name: CI

on:
pull_request:
branches: [main]
paths-ignore:
- "docs/**"
- "*.md"
- "LICENSE"
push:
branches: [main]

concurrency:
group: ci-${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}

permissions:
contents: read

jobs:
lint:
name: Lint & Format
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
with:
persist-credentials: false

- uses: pnpm/action-setup@0ebf47130e4866e96fce0953f49152a61190b271 # v6.0.9

- uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0
with:
node-version-file: .nvmrc
cache: pnpm

- run: pnpm install --frozen-lockfile

- name: Generate Wrangler types
run: pnpm types

- name: Oxlint
run: pnpm lint

- name: Oxfmt
run: pnpm format:check

test:
name: Test
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
with:
persist-credentials: false

- uses: pnpm/action-setup@0ebf47130e4866e96fce0953f49152a61190b271 # v6.0.9

- uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0
with:
node-version-file: .nvmrc
cache: pnpm

- run: pnpm install --frozen-lockfile

- name: Generate Wrangler types
run: pnpm types

- name: Run tests
run: pnpm --filter @uploads/storage test && pnpm --filter @buildinternet/uploads test
1 change: 1 addition & 0 deletions .nvmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
22.14.0
22 changes: 22 additions & 0 deletions .oxfmtrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
{
"$schema": "./node_modules/oxfmt/configuration_schema.json",
"semi": true,
"singleQuote": false,
"trailingComma": "all",
"printWidth": 100,
"tabWidth": 2,
"useTabs": false,
"arrowParens": "always",
"endOfLine": "lf",
"sortPackageJson": false,
"ignorePatterns": [
"node_modules",
".wrangler",
"apps/web/dist",
"apps/web/.astro",
"**/*.d.ts",
"pnpm-lock.yaml",
"packages/*/dist",
".superpowers"
]
}
111 changes: 111 additions & 0 deletions .oxlintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
{
"$schema": "./node_modules/oxlint/configuration_schema.json",
"plugins": ["typescript", "unicorn", "oxc"],
"options": {
"typeAware": true,
"typeCheck": true
},
"categories": {
"correctness": "error",
"suspicious": "warn",
"perf": "warn"
},
"rules": {
"no-console": "off",
"no-underscore-dangle": "off",
"no-await-in-loop": "off",
"no-unused-vars": ["warn", { "argsIgnorePattern": "^_", "varsIgnorePattern": "^_" }],
"typescript/no-explicit-any": "off",
"typescript/no-non-null-assertion": "off",
"unicorn/no-null": "off",
"unicorn/no-array-reduce": "off",
"unicorn/no-await-expression-member": "off",

"typescript/await-thenable": "error",
"typescript/consistent-return": "off",
"typescript/consistent-type-exports": "off",
"typescript/dot-notation": "off",
"typescript/no-array-delete": "off",
"typescript/no-base-to-string": "off",
"typescript/no-confusing-void-expression": "off",
"typescript/no-deprecated": "off",
"typescript/no-duplicate-type-constituents": "off",
"typescript/no-floating-promises": "error",
"typescript/no-for-in-array": "off",
"typescript/no-implied-eval": "off",
"typescript/no-meaningless-void-operator": "off",
"typescript/no-misused-promises": [
"error",
{
"checksVoidReturn": {
"attributes": false
}
}
],
"typescript/no-misused-spread": "off",
"typescript/no-mixed-enums": "off",
"typescript/no-redundant-type-constituents": "off",
"typescript/no-unnecessary-boolean-literal-compare": "off",
"typescript/no-unnecessary-condition": "off",
"typescript/no-unnecessary-qualifier": "off",
"typescript/no-unnecessary-template-expression": "off",
"typescript/no-unnecessary-type-arguments": "off",
"typescript/no-unnecessary-type-assertion": "off",
"typescript/no-unnecessary-type-conversion": "off",
"typescript/no-unnecessary-type-parameters": "off",
"typescript/no-unsafe-argument": "off",
"typescript/no-unsafe-assignment": "off",
"typescript/no-unsafe-call": "off",
"typescript/no-unsafe-enum-comparison": "off",
"typescript/no-unsafe-member-access": "off",
"typescript/no-unsafe-return": "off",
"typescript/no-unsafe-type-assertion": "off",
"typescript/no-unsafe-unary-minus": "off",
"typescript/no-useless-default-assignment": "off",
"typescript/non-nullable-type-assertion-style": "off",
"typescript/only-throw-error": "off",
"typescript/prefer-find": "off",
"typescript/prefer-includes": "off",
"typescript/prefer-nullish-coalescing": "off",
"typescript/prefer-optional-chain": "off",
"typescript/prefer-promise-reject-errors": "off",
"typescript/prefer-readonly-parameter-types": "off",
"typescript/prefer-readonly": "off",
"typescript/prefer-reduce-type-parameter": "off",
"typescript/prefer-regexp-exec": "off",
"typescript/prefer-return-this-type": "off",
"typescript/prefer-string-starts-ends-with": "off",
"typescript/promise-function-async": "off",
"typescript/related-getter-setter-pairs": "off",
"typescript/require-array-sort-compare": "off",
"typescript/require-await": "off",
"typescript/restrict-plus-operands": "off",
"typescript/restrict-template-expressions": "off",
"typescript/return-await": "off",
"typescript/strict-boolean-expressions": "off",
"typescript/strict-void-return": "off",
"typescript/switch-exhaustiveness-check": "off",
"typescript/unbound-method": "off",
"typescript/use-unknown-in-catch-callback-variable": "off"
},
"overrides": [
{
"files": ["**/*.test.ts", "packages/storage/test/**", "packages/uploads/test/**"],
"rules": {
"typescript/no-floating-promises": "off",
"typescript/await-thenable": "off",
"unicorn/no-array-sort": "off"
}
}
],
"ignorePatterns": [
"node_modules",
".wrangler",
"apps/web/dist",
"apps/web/.astro",
"**/*.d.ts",
"packages/*/dist/**",
"apps/api/scripts/**",
".superpowers/**"
]
}
18 changes: 9 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,8 @@ register with `--bucket` and the record points at a dedicated bucket (own
binding or S3 credentials). Nothing in the code treats any workspace as special.
The default workspace ships ready to use:

| Workspace | Bucket | Public base URL |
|---|---|---|
| Workspace | Bucket | Public base URL |
| --------- | ----------------- | ---------------------------------------------- |
| `default` | `uploads-default` | `https://storage.uploads.sh` — generic hosting |

Workspace records live in the `REGISTRY` KV namespace (`ws:<name>`). Each
Expand Down Expand Up @@ -105,13 +105,13 @@ curl -XDELETE https://api.uploads.sh/admin/tokens \
All `/v1` routes require the workspace's `Authorization: Bearer <token>`.
Unknown workspaces and bad tokens are indistinguishable (both 401).

| Route | Description |
|---|---|
| `GET /health` | Liveness (no auth) |
| `PUT /v1/:workspace/files/:key` | Upload raw body; `Content-Type` header is stored. Returns `{ workspace, key, url, size }` |
| `GET /v1/:workspace/files?prefix=&limit=&cursor=` | List objects |
| `GET /v1/:workspace/files/:key` | Object metadata |
| `DELETE /v1/:workspace/files/:key` | Delete object |
| Route | Description |
| ------------------------------------------------- | ----------------------------------------------------------------------------------------- |
| `GET /health` | Liveness (no auth) |
| `PUT /v1/:workspace/files/:key` | Upload raw body; `Content-Type` header is stored. Returns `{ workspace, key, url, size }` |
| `GET /v1/:workspace/files?prefix=&limit=&cursor=` | List objects |
| `GET /v1/:workspace/files/:key` | Object metadata |
| `DELETE /v1/:workspace/files/:key` | Delete object |

`url` in responses is the public URL when the workspace has a
`publicBaseUrl`, otherwise `null`.
Expand Down
36 changes: 26 additions & 10 deletions apps/api/scripts/add-workspace.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,17 @@ for (let i = 0; i < rest.length; i++) {
const flag = rest[i];
if (!flag.startsWith("--")) fail(`unexpected argument: ${flag}`);
const key = flag.slice(2);
if (key === "local") { opts.local = true; continue; }
if (key === "local") {
opts.local = true;
continue;
}
opts[key] = rest[++i];
}

function fail(msg) { console.error(`error: ${msg}`); process.exit(1); }
function fail(msg) {
console.error(`error: ${msg}`);
process.exit(1);
}

if (!name || !/^[a-z0-9][a-z0-9-]{1,62}$/.test(name)) {
fail("workspace name must be lowercase alphanumeric/hyphens, 2-63 chars");
Expand All @@ -48,11 +54,13 @@ const SHARED = {
publicBaseUrl: "https://storage.uploads.sh",
};

const tokens = [{
hash: crypto.createHash("sha256").update(token).digest("hex"),
label: "initial",
createdAt: new Date().toISOString(),
}];
const tokens = [
{
hash: crypto.createHash("sha256").update(token).digest("hex"),
label: "initial",
createdAt: new Date().toISOString(),
},
];

const record = opts.bucket
? {
Expand Down Expand Up @@ -85,9 +93,15 @@ Object.keys(record).forEach((k) => record[k] === undefined && delete record[k]);
execFileSync(
"pnpm",
[
"exec", "wrangler", "kv", "key", "put", `ws:${name}`,
"exec",
"wrangler",
"kv",
"key",
"put",
`ws:${name}`,
JSON.stringify(record),
"--binding", "REGISTRY",
"--binding",
"REGISTRY",
opts.local ? "--local" : "--remote",
],
{ stdio: "inherit" },
Expand All @@ -96,4 +110,6 @@ execFileSync(
console.log(`\nworkspace : ${name}`);
console.log(`token : ${token}`);
console.log("\nStore the token now — only its hash is kept in KV.");
console.log(`try it : curl -H "Authorization: Bearer ${token}" https://api.uploads.sh/v1/${name}/files`);
console.log(
`try it : curl -H "Authorization: Bearer ${token}" https://api.uploads.sh/v1/${name}/files`,
);
17 changes: 13 additions & 4 deletions apps/api/src/routes/admin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,13 @@ const WS_NAME_RE = /^[a-z0-9][a-z0-9-]{1,62}$/;
const HASH_PREFIX_LEN = 8;

/** Token list for a record, migrating a legacy `tokenHash`-only record into the list shape. */
function migrateTokens(record: WorkspaceRecord): { hash: string; label?: string; createdAt: string }[] {
return record.tokens ?? (record.tokenHash ? [{ hash: record.tokenHash, createdAt: new Date(0).toISOString() }] : []);
function migrateTokens(
record: WorkspaceRecord,
): { hash: string; label?: string; createdAt: string }[] {
return (
record.tokens ??
(record.tokenHash ? [{ hash: record.tokenHash, createdAt: new Date(0).toISOString() }] : [])
);
}

export const admin = new Hono<{ Bindings: Env }>()
Expand All @@ -26,8 +31,12 @@ export const admin = new Hono<{ Bindings: Env }>()
const record = await c.env.REGISTRY.get<WorkspaceRecord>(`ws:${name}`, { type: "json" });
if (!record) return c.json({ error: "workspace not found" }, 404);

const token = `up_${name}_${btoa(String.fromCharCode(...crypto.getRandomValues(new Uint8Array(24))))
.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "")}`;
const token = `up_${name}_${btoa(
String.fromCharCode(...crypto.getRandomValues(new Uint8Array(24))),
)
.replace(/\+/g, "-")
.replace(/\//g, "_")
.replace(/=+$/, "")}`;
const entry = { hash: await sha256Hex(token), label, createdAt: new Date().toISOString() };

const tokens = migrateTokens(record);
Expand Down
7 changes: 5 additions & 2 deletions apps/api/src/routes/files.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { Hono } from "hono";
import { publicUrl, storage, storageConfig } from "../storage";
import type { WorkspaceVars } from "../workspace";

const KEY_RE = /^[\w!*'().\/-]+$/;
const KEY_RE = /^[\w!*'()./-]+$/;

function badKey(key: string): boolean {
return (
Expand All @@ -26,7 +26,10 @@ export const files = new Hono<WorkspaceVars>()
await storage(c.env, ws).upload(key, new Uint8Array(body), { contentType });

const url = publicUrl(storageConfig(c.env, ws), key);
return c.json({ workspace: c.get("workspaceName"), key, url, size: body.byteLength, contentType }, 201);
return c.json(
{ workspace: c.get("workspaceName"), key, url, size: body.byteLength, contentType },
201,
);
})

// List
Expand Down
Loading