mirror of
https://github.com/HeyPuter/puter.git
synced 2026-11-13 20:12:57 -10:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a2de5e3da2 | ||
|
|
458f2eae4c | ||
|
|
c166560ff4 | ||
|
|
331d9e7542 | ||
|
|
ec31007c4b | ||
|
|
e615c7ee7f | ||
|
|
35d4d4f755 | ||
|
|
195468c4e1 | ||
|
|
15f274e662 | ||
|
|
7cb898457c | ||
|
|
aa4050ee32 | ||
|
|
f392de722a | ||
|
|
07d95d5d3c | ||
|
|
22c61d8221 | ||
|
|
8fb0a66ef2 | ||
|
|
d5cd828cba | ||
|
|
0119ae36a8 | ||
|
|
87852d125f | ||
|
|
d3969b0122 | ||
|
|
3cba4cab1e | ||
|
|
ef35a04c4a | ||
|
|
874928e845 | ||
|
|
c3d1574f8c | ||
|
|
eee5c9e48b | ||
|
|
2f5780d1d1 | ||
|
|
fa60f66057 | ||
|
|
a741bd5419 | ||
|
|
4d2d4a7ca3 | ||
|
|
5c1e6ab16b | ||
|
|
f5f75dbef8 | ||
|
|
6577051d64 | ||
|
|
b2f5cc11b5 | ||
|
|
a1252f66cc | ||
|
|
e8d9e8b42b | ||
|
|
ced7265eb0 | ||
|
|
14098b2ff2 | ||
|
|
fb93a0863b | ||
|
|
4088bff216 | ||
|
|
915152d3b9 | ||
|
|
2ecea9a7b0 | ||
|
|
dc2a620b4e | ||
|
|
8648a303f1 | ||
|
|
6a65ca4ebd | ||
|
|
58b83c27f2 | ||
|
|
338d925bcc | ||
|
|
7e2c4a0a1c | ||
|
|
9822be5df4 | ||
|
|
cf5c62bcfc | ||
|
|
27553ef926 | ||
|
|
3f249fcc89 | ||
|
|
c3654ab148 | ||
|
|
0e9e8d41d9 | ||
|
|
2f49c1c9b0 | ||
|
|
072dbe8db5 | ||
|
|
da208e23f5 | ||
|
|
222a617c44 | ||
|
|
e355c77a4a | ||
|
|
639653dac2 | ||
|
|
0aa5543397 | ||
|
|
dfdda4f3b9 | ||
|
|
8cf58d7fc6 | ||
|
|
4783e3eae4 | ||
|
|
4931ad3960 | ||
|
|
5ad78a5ebb | ||
|
|
dc95f2e065 | ||
|
|
0361ceba6c | ||
|
|
4ecc7372f9 | ||
|
|
dbcd627815 | ||
|
|
6061c81c36 | ||
|
|
c1aee61da1 | ||
|
|
f0d3346ca7 | ||
|
|
e8ca6376be | ||
|
|
c48c134869 | ||
|
|
49e334521d | ||
|
|
04a641adc2 | ||
|
|
2210652643 | ||
|
|
8713db3d55 | ||
|
|
f2e8b5ee3e | ||
|
|
7e0c6c6470 | ||
|
|
19c49db538 | ||
|
|
ea40ac1e53 | ||
|
|
653898b463 | ||
|
|
c07d0a2bc7 | ||
|
|
9bb221a0d7 | ||
|
|
e4f2c4a28b | ||
|
|
3a4858b83c | ||
|
|
826ea36502 | ||
|
|
397819d45e | ||
|
|
66fecf88ef | ||
|
|
e8dc220981 | ||
|
|
1c2b05d8f6 | ||
|
|
f3495f3098 | ||
|
|
081b093e7e | ||
|
|
4d30753958 | ||
|
|
c72e0cb0e0 | ||
|
|
25f8dbf120 | ||
|
|
868202ba41 | ||
|
|
c6b0ed32bf | ||
|
|
17adef11a6 | ||
|
|
6d1c807879 | ||
|
|
0ed5b20627 | ||
|
|
f5175941d9 | ||
|
|
e2f048ec2d | ||
|
|
2717444c29 | ||
|
|
b21755b5a3 | ||
|
|
37ff97b52f | ||
|
|
b897598fac | ||
|
|
95cb92abed | ||
|
|
5730dc642a | ||
|
|
7c2a3b4612 | ||
|
|
dbf796d698 | ||
|
|
7f739a53f8 | ||
|
|
2dbde52338 | ||
|
|
61f1caa122 | ||
|
|
695d7b8654 | ||
|
|
6e7fd2ca95 | ||
|
|
79bfcf226b | ||
|
|
9d9e091a7a | ||
|
|
be1bb6bc06 | ||
|
|
d39bb412f3 | ||
|
|
e71b586fe5 | ||
|
|
2fcac12340 | ||
|
|
0847395c92 | ||
|
|
49c3df2328 | ||
|
|
58192cacb3 | ||
|
|
b81284e2c6 | ||
|
|
5b39e39e1f | ||
|
|
b944217410 | ||
|
|
dca7304be9 | ||
|
|
61a4b10adf | ||
|
|
231878266c | ||
|
|
51bf8fdde6 | ||
|
|
18134629d2 | ||
|
|
f6b737e45d | ||
|
|
3b7be8a719 | ||
|
|
aae1d194c7 | ||
|
|
ef0da306a8 | ||
|
|
bfaaa914f1 | ||
|
|
2f101c4a39 | ||
|
|
765eb43568 | ||
|
|
aa61e005e5 | ||
|
|
5b2e2b037b | ||
|
|
bcfd685826 | ||
|
|
5d8d25f370 | ||
|
|
6679318207 | ||
|
|
255e80d077 | ||
|
|
965d99d137 | ||
|
|
3b65523da9 | ||
|
|
3cfee32ae0 | ||
|
|
497c633b8a | ||
|
|
df45e22813 | ||
|
|
199b68a964 | ||
|
|
8db8ec3574 | ||
|
|
4a36670417 | ||
|
|
77ac503bfc | ||
|
|
be55e447bb | ||
|
|
00e9f922c0 | ||
|
|
361e51060a | ||
|
|
fbbc73308e | ||
|
|
a31e4c19cb | ||
|
|
b69a85f10e | ||
|
|
d919b1f312 | ||
|
|
cb81579c53 | ||
|
|
0306a395a2 | ||
|
|
5fbbfb4c18 | ||
|
|
b725c4c7b4 | ||
|
|
24e3ec89f3 | ||
|
|
f8d3fdbefb | ||
|
|
352f1bc23e | ||
|
|
413cb79683 | ||
|
|
d06f856e46 | ||
|
|
09c3cc6db1 | ||
|
|
eb96dd952b | ||
|
|
1da3a769c4 | ||
|
|
356a3284fa | ||
|
|
0eedcf567e | ||
|
|
f4f58dbfb9 | ||
|
|
8135e076c2 | ||
|
|
22b3415866 | ||
|
|
5effca4bbc | ||
|
|
aa14541e50 | ||
|
|
13525c85a0 | ||
|
|
2f6f7e39bb | ||
|
|
2d76025c9c | ||
|
|
bb9edc4f65 | ||
|
|
afcd821f50 | ||
|
|
b8e66cada9 | ||
|
|
fc5025a2a8 | ||
|
|
e3d238f897 | ||
|
|
9ab3e3ccd8 | ||
|
|
7abf5faa3c | ||
|
|
4052c7995c | ||
|
|
776b6831f3 | ||
|
|
a2d231dc23 | ||
|
|
1aeedd8696 | ||
|
|
09bf422686 | ||
|
|
18b3e06fe8 | ||
|
|
e436693d3e | ||
|
|
eb66848aee | ||
|
|
0eded34c8c | ||
|
|
367c18bfc5 | ||
|
|
92dc0a7671 | ||
|
|
8e553b4ee0 | ||
|
|
21c64e827b | ||
|
|
c69a0abfa9 | ||
|
|
cce6531d45 | ||
|
|
84a31b3520 | ||
|
|
59cdb6e8c6 | ||
|
|
068e620249 | ||
|
|
80aa87023e | ||
|
|
626d63c91d | ||
|
|
5bf0411015 | ||
|
|
b2fcb8d104 | ||
|
|
79f98795c7 | ||
|
|
24ad365047 | ||
|
|
72286fd642 | ||
|
|
a0f46c326a | ||
|
|
b1f2750cdb | ||
|
|
8aee3f8174 | ||
|
|
ea61799b3d | ||
|
|
b1e6e0c25a | ||
|
|
f7916cfa74 | ||
|
|
3f37ef2fad | ||
|
|
3297940bab | ||
|
|
821d33b8d8 | ||
|
|
72129ca16f | ||
|
|
12fa88b149 | ||
|
|
c83069bd03 | ||
|
|
5661605884 | ||
|
|
d1bbbb8e93 | ||
|
|
178f851684 | ||
|
|
cb4b8c5914 | ||
|
|
8018a607a8 | ||
|
|
dc5a7ca431 | ||
|
|
95d33eab94 | ||
|
|
725cbf2e20 | ||
|
|
674cebd9e1 | ||
|
|
0dd66463df | ||
|
|
beeeb7bcbf | ||
|
|
bf4bc214b2 | ||
|
|
b99534ebdf | ||
|
|
c6fb75c65f | ||
|
|
38e8b19b50 | ||
|
|
90ce840234 | ||
|
|
fc6eda392b | ||
|
|
343edbff51 | ||
|
|
fe88880486 | ||
|
|
1c2e4968e2 | ||
|
|
f9b375a39b | ||
|
|
eb18e74e88 | ||
|
|
487553a00c | ||
|
|
c78927d5db | ||
|
|
26e9822344 | ||
|
|
207fa139d4 | ||
|
|
e2236d43fd | ||
|
|
6006767a9f | ||
|
|
35abf9a6bc | ||
|
|
c3a4223bbf | ||
|
|
4a2fa5a29f | ||
|
|
17ae6668b4 | ||
|
|
06a31fd67b | ||
|
|
1a13ef6921 | ||
|
|
17a323298c | ||
|
|
27c99fd90a | ||
|
|
6c7175c109 | ||
|
|
cdd9dbf748 | ||
|
|
1b72b80241 | ||
|
|
be53a9472a | ||
|
|
accdec3af4 | ||
|
|
95b6dbd140 | ||
|
|
08838c989e | ||
|
|
74bff84226 | ||
|
|
b1a3124fcc | ||
|
|
3e1c7eb434 | ||
|
|
2125367683 | ||
|
|
809e33b053 | ||
|
|
0efe163591 | ||
|
|
e8935f5582 | ||
|
|
0da9e1fab3 | ||
|
|
802370eb9d | ||
|
|
4e722b47b5 | ||
|
|
b055c5cdad | ||
|
|
b7a1f21e31 | ||
|
|
a04cac60e6 | ||
|
|
274b69d017 | ||
|
|
5fab338ba1 | ||
|
|
6cd77384a5 | ||
|
|
5290d78e20 | ||
|
|
2ce02db1b5 | ||
|
|
fff46a6b63 | ||
|
|
369037e269 | ||
|
|
6f7264b60b | ||
|
|
9881fecacd | ||
|
|
cf9338c35f | ||
|
|
a9947ad97f | ||
|
|
ac2e3e2873 | ||
|
|
8f4eb5627b | ||
|
|
e4bd62b84c | ||
|
|
0e033348f0 | ||
|
|
0651aab1be | ||
|
|
f8a7f1c1f9 | ||
|
|
c90931d004 | ||
|
|
a973f66092 | ||
|
|
5d81ff4cbe | ||
|
|
7442b48157 | ||
|
|
59003a9ab9 | ||
|
|
40c2e3f442 | ||
|
|
65b61fc90d | ||
|
|
05c6cd6c3d | ||
|
|
15fcc5680f | ||
|
|
fdd9f30c39 | ||
|
|
0049c9ef00 | ||
|
|
f097f2e10a | ||
|
|
4009f4f331 | ||
|
|
8f8b7f0fbf | ||
|
|
29b3b4ecba | ||
|
|
b111e05ef7 | ||
|
|
c2f73c37c5 | ||
|
|
92b3f4ff76 | ||
|
|
1cdda3dda8 | ||
|
|
a8a03d3f87 | ||
|
|
5eebc9a5de | ||
|
|
cc648be854 | ||
|
|
483e2835c4 | ||
|
|
daa90286d3 | ||
|
|
5e1d6a7db3 | ||
|
|
ab4f222e92 | ||
|
|
5da46a15fb | ||
|
|
9438355a36 |
No files matched your search
@@ -1,3 +1,4 @@
|
||||
.dockerignore
|
||||
Dockerfile
|
||||
node_modules
|
||||
/puter
|
||||
@@ -0,0 +1,25 @@
|
||||
---
|
||||
name: Bug report
|
||||
about: Create a report to help us improve
|
||||
title: ''
|
||||
labels: ''
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
**Issue Description**
|
||||
|
||||
**Steps to Reproduce**
|
||||
|
||||
**Expected & Actual Behavior**
|
||||
|
||||
**Addition Information or Screenshots (if applicable)**
|
||||
|
||||
**Deployment**
|
||||
- [ ] Production (puter.com)
|
||||
- [ ] Development (`npm run start`)
|
||||
- [ ] Docker (via `docker run`)
|
||||
- [ ] Docker (via `docker-compose`)
|
||||
|
||||
**Puter version (if accessible)**
|
||||
> Click the profile button on the top-right, then "Settings". The version number will be printed at the bottom
|
||||
@@ -0,0 +1,10 @@
|
||||
---
|
||||
name: Driver Request
|
||||
about: Request a driver on Puter
|
||||
title: ''
|
||||
labels: ''
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
> Drivers are services that apps on Puter can use. For example, drivers support many of the features in the [Puter SDK](https://docs.puter.com/). If you're not sure if what you're suggesting is a driver, you should use the "Feature Request" template instead.
|
||||
@@ -0,0 +1,10 @@
|
||||
---
|
||||
name: Feature request
|
||||
about: Suggest an idea for Puter
|
||||
title: ''
|
||||
labels: idea
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
---
|
||||
name: Idea for Improvement
|
||||
about: An enhancement for an existing feature on Puter
|
||||
title: ''
|
||||
labels: enhancement
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
# This workflow will do a clean installation of node dependencies, cache/restore them, build the source code and run tests across different versions of node
|
||||
# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-nodejs
|
||||
|
||||
name: Node.js CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ "main" ]
|
||||
pull_request:
|
||||
branches: [ "main" ]
|
||||
|
||||
jobs:
|
||||
build:
|
||||
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
strategy:
|
||||
matrix:
|
||||
node-version: [16.x, 18.x, 20.x, 21.x]
|
||||
# See supported Node.js release schedule at https://nodejs.org/en/about/releases/
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Use Node.js ${{ matrix.node-version }}
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: ${{ matrix.node-version }}
|
||||
cache: 'npm'
|
||||
- run: npm ci
|
||||
- run: npm run build --if-present
|
||||
- run: npm test
|
||||
@@ -5,7 +5,7 @@ name: Docker Image CI
|
||||
# branch called `main`.
|
||||
on:
|
||||
push:
|
||||
branches: ['main']
|
||||
branches: ['release']
|
||||
|
||||
|
||||
# Defines two custom environment variables for the workflow. These are used
|
||||
@@ -40,6 +40,12 @@ jobs:
|
||||
registry: ${{ env.REGISTRY }}
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v3
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v2
|
||||
|
||||
# This step uses [docker/metadata-action](https://github.com/docker/metadata-action#about)
|
||||
# to extract tags and labels that will be applied to the specified image.
|
||||
@@ -73,6 +79,7 @@ jobs:
|
||||
- name: Build and push Docker image
|
||||
uses: docker/build-push-action@v5
|
||||
with:
|
||||
platforms: linux/amd64,linux/arm64
|
||||
context: .
|
||||
push: true
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
name: Maintain Release Merge PR
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
|
||||
jobs:
|
||||
update-release-pr:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- name: Setup Git
|
||||
run: |
|
||||
git config user.name github-actions
|
||||
git config user.email [email protected]
|
||||
- name: Check for existing PR
|
||||
id: find-pr
|
||||
uses: juliangruber/find-pull-request-action@v1
|
||||
with:
|
||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
branch: release
|
||||
- uses: actions/checkout@v4
|
||||
if: steps.find-pr.outputs.number == ''
|
||||
with:
|
||||
ref: release
|
||||
- name: Reset release branch
|
||||
if: steps.find-pr.outputs.number == ''
|
||||
run: |
|
||||
git fetch origin main:main
|
||||
git reset --hard main
|
||||
- name: Create/Update PR
|
||||
if: steps.find-pr.outputs.number == ''
|
||||
uses: peter-evans/create-pull-request@v6
|
||||
with:
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
commit-message: Update release branch
|
||||
title: Merge Release Auto-PR
|
||||
body: Merging this PR will invoke release actions
|
||||
branch: auto-update/release
|
||||
@@ -0,0 +1,18 @@
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
pull-requests: write
|
||||
|
||||
name: release-please
|
||||
|
||||
jobs:
|
||||
release-please:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: google-github-actions/release-please-action@v4
|
||||
with:
|
||||
release-type: node
|
||||
+2
-1
@@ -8,4 +8,5 @@ dist/
|
||||
.vscode/
|
||||
.env
|
||||
# this is for jetbrain IDEs
|
||||
.idea/
|
||||
.idea/
|
||||
/puter
|
||||
@@ -0,0 +1,17 @@
|
||||
# Changelog
|
||||
|
||||
## [2.2.0](https://github.com/HeyPuter/puter/compare/v2.1.1...v2.2.0) (2024-04-23)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* add /healthcheck endpoint ([c166560](https://github.com/HeyPuter/puter/commit/c166560ff4ab5a453d3ec4f97326c995deb7f522))
|
||||
* allow apps to add a menubar via puter.js ([331d9e7](https://github.com/HeyPuter/puter/commit/331d9e75428ec7609394f59b1755374c7340f83e))
|
||||
|
||||
## [2.1.1](https://github.com/HeyPuter/puter/compare/v2.1.0...v2.1.1) (2024-04-22)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* test release-please action [#3](https://github.com/HeyPuter/puter/issues/3) ([8fb0a66](https://github.com/HeyPuter/puter/commit/8fb0a66ef21921990e564e5f61c0e80e7f929dc7))
|
||||
* test release-please action [#4](https://github.com/HeyPuter/puter/issues/4) ([f392de7](https://github.com/HeyPuter/puter/commit/f392de722a5232b622ed91b656a31cdc443c2e84))
|
||||
@@ -57,6 +57,28 @@ See [doc/contributors/index.md](./doc/contributors/index.md) for more informatio
|
||||
|
||||
<br>
|
||||
|
||||
## Commit Messages
|
||||
|
||||
Use the imperative, as is the convention in the Linux kernel:
|
||||
|
||||
- correct: `Improve performance of readdir`
|
||||
- incorrect: `Improved readdir`
|
||||
- incorrect: `Improving readdir`
|
||||
|
||||
We have the following exceptions to this rule:
|
||||
- If the commit message is in _past tense_, it's a shorthand for the following:
|
||||
- `Apply changes that would be applied after one had <past tense message>`
|
||||
- If the commit message is in _present tense_, it's shorthand for the following:
|
||||
- `Apply changes that would be applied after <present-tense message>`
|
||||
|
||||
For example, the following are correct:
|
||||
- `Improved readdir`
|
||||
- interpret this as: `Apply changes that would be applied after one had improved readdir`
|
||||
- `Improving readdir`
|
||||
- interpret this as: `Apply changes that would be applied after improving readdir`
|
||||
|
||||
<br>
|
||||
|
||||
## Code Review
|
||||
|
||||
Once you've submitted your pull request, the project maintainers will review your changes. We may suggest some changes or improvements. This is a normal part of the process, and your contributions are greatly appreciated!
|
||||
|
||||
+45
-11
@@ -1,30 +1,64 @@
|
||||
# /!\ NOTICE /!\
|
||||
|
||||
# Many of the developers DO NOT USE the Dockerfile or image.
|
||||
# While we do test new changes to Docker configuration, it's
|
||||
# possible that future changes to the repo might break it.
|
||||
# When changing this file, please try to make it as resiliant
|
||||
# to such changes as possible; developers shouldn't need to
|
||||
# worry about Docker unless the build/run process changes.
|
||||
|
||||
# Build stage
|
||||
FROM node:21-alpine AS build
|
||||
|
||||
# Install build dependencies
|
||||
RUN apk add --no-cache git python3 make g++ \
|
||||
&& ln -sf /usr/bin/python3 /usr/bin/python
|
||||
|
||||
# Set up working directory
|
||||
WORKDIR /app
|
||||
|
||||
# Copy package.json and package-lock.json
|
||||
COPY package*.json ./
|
||||
|
||||
# Copy the source files
|
||||
COPY . .
|
||||
|
||||
# Install node modules
|
||||
RUN npm cache clean --force \
|
||||
&& npm ci
|
||||
|
||||
# Run the build command if necessary
|
||||
RUN npm run build
|
||||
|
||||
# Production stage
|
||||
FROM node:21-alpine
|
||||
|
||||
# Set labels
|
||||
LABEL repo="https://github.com/HeyPuter/puter"
|
||||
LABEL license="AGPL-3.0,https://github.com/HeyPuter/puter/blob/master/LICENSE.txt"
|
||||
LABEL version="v1.2.40-beta"
|
||||
LABEL version="1.2.46-beta-1"
|
||||
|
||||
# Debugging
|
||||
RUN apk add --no-cache bash # useful for debugging
|
||||
# Install git (required by Puter to check version)
|
||||
RUN apk add --no-cache git
|
||||
|
||||
# Setup working directory
|
||||
# Set up working directory
|
||||
RUN mkdir -p /opt/puter/app
|
||||
WORKDIR /opt/puter/app
|
||||
|
||||
# Add source files
|
||||
# NOTE: This might change (https://github.com/HeyPuter/puter/discussions/32)
|
||||
# Copy built artifacts and necessary files from the build stage
|
||||
COPY --from=build /app/dist ./dist
|
||||
COPY --from=build /app/node_modules ./node_modules
|
||||
COPY . .
|
||||
|
||||
# Set permissions
|
||||
RUN chown -R node:node /opt/puter/app
|
||||
USER node
|
||||
|
||||
# Install node modules
|
||||
RUN npm cache clean --force \
|
||||
&& npm install
|
||||
EXPOSE 4100
|
||||
|
||||
EXPOSE 4000
|
||||
HEALTHCHECK --interval=30s --timeout=3s \
|
||||
CMD wget --no-verbose --tries=1 --spider http://puter.localhost:4100/test || exit 1
|
||||
|
||||
ENV NO_VAR_RUNTUME=1
|
||||
|
||||
CMD [ "npm", "start" ]
|
||||
CMD ["npm", "start"]
|
||||
@@ -1,6 +1,6 @@
|
||||
<h3 align="center"><img width="80" alt="Puter.com, The Personal Cloud Computer: All your files, apps, and games in one place accessible from anywhere at any time." src="https://assets.puter.site/puter-logo.png"></h3>
|
||||
|
||||
<h3 align="center">The Internet OS! Free, Open-Source, and Self-Hostable!</h3>
|
||||
<h3 align="center">The Internet OS! Free, Open-Source, and Self-Hostable.</h3>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://puter.com/"><strong>« LIVE DEMO »</strong></a>
|
||||
@@ -15,6 +15,8 @@
|
||||
<a href="https://reddit.com/r/puter">Reddit</a>
|
||||
·
|
||||
<a href="https://twitter.com/HeyPuter">X (Twitter)</a>
|
||||
·
|
||||
<a href="https://hackerone.com/puter_h1b">Bug Bounty</a>
|
||||
</p>
|
||||
|
||||
<h3 align="center"><img width="700" style="border-radius:5px;" alt="screenshot" src="https://assets.puter.site/puter.com-screenshot-2.webp"></h3>
|
||||
@@ -29,6 +31,10 @@ Puter is an advanced, open-source internet operating system designed to be featu
|
||||
|
||||
## Getting Started
|
||||
|
||||
After reading this section, please proceed to **Self-Hosting** and **Configuration** below.
|
||||
Read these instructions carefully or you may see errors due to
|
||||
an invalid setup.
|
||||
|
||||
### Local Development
|
||||
|
||||
```bash
|
||||
@@ -44,19 +50,79 @@ This will launch Puter at http://localhost:4000 (or the next available port).
|
||||
|
||||
### Using Docker
|
||||
|
||||
**note:** it is **not** necessary to run this within a clone of this repository. For contributors, it is recommended to use the [Local Development](#local-development) instructions.
|
||||
|
||||
```bash
|
||||
git clone https://github.com/HeyPuter/puter
|
||||
cd puter
|
||||
mkdir puter && cd puter && mkdir -p puter/config puter/data && sudo chown -R 1000:1000 puter && docker run --rm -p 4100:4100 -v `pwd`/puter/config:/etc/puter -v `pwd`/puter/data:/var/puter ghcr.io/heyputer/puter
|
||||
```
|
||||
|
||||
### Using Docker Compose
|
||||
|
||||
**note:** it is **not** necessary to run this within a clone of this repository. For contributors, it is recommended to use the [Local Development](#local-development) instructions.
|
||||
|
||||
```bash
|
||||
mkdir -p puter/config puter/data
|
||||
sudo chown -R 1000:1000 puter
|
||||
wget https://raw.githubusercontent.com/HeyPuter/puter/main/docker-compose.yml
|
||||
docker compose up
|
||||
```
|
||||
|
||||
<br/>
|
||||
|
||||
See [Configuration](#configuration) for next steps.
|
||||
|
||||
<br/>
|
||||
|
||||
## ⚠️ Self-Hosting ⚠️
|
||||
The self-hosted version of Puter is currently in alpha stage and should not be used in production yet. It is under active development and may contain bugs, other issues. Please exercise caution and use it for testing and evaluation purposes only.
|
||||
|
||||
<br/>
|
||||
|
||||
## Configuration
|
||||
|
||||
Running the server will generate a configuration file in one of these locations:
|
||||
- `config/config.json` when [Using Docker](#using-docker)
|
||||
- `volatile/config/config.json` in [Local Development](#local-development)
|
||||
- `/etc/puter/config.json` on a server (or within a Docker container)
|
||||
|
||||
### Domain Name
|
||||
|
||||
To access Puter on your device, you can simply go to the address printed in
|
||||
the server console (usually `puter.localhost:4100`).
|
||||
|
||||
To access Puter from another device, a domain name must be configured, as well as
|
||||
an `api` subdomain. For example, `example.local` might be the domain name pointing
|
||||
to the IP address of the server running puter, and `api.example.com` must point to
|
||||
this address as well. This domain must be specified in the configuration file
|
||||
(usually `volatile/config/config.json`) as well.
|
||||
|
||||
See [domain configuration](./doc/self-hosters/domains.md) for more information.
|
||||
|
||||
### Configure the Port
|
||||
|
||||
- You can specify a custom port by setting `http_port` to a desired value
|
||||
- If you're using a reverse-proxy such as nginx or cloudflare, you should
|
||||
also set `pub_port` to the public (external) port (usually `443`)
|
||||
- If you have HTTPS enabled on your reverse-proxy, ensure that
|
||||
`protocol` in config.json is set accordingly
|
||||
|
||||
### Default User
|
||||
|
||||
By default, Puter will create a user called `default_user`.
|
||||
This user will have a randomly generated password, which will be printed
|
||||
in the development console.
|
||||
A warning will persist in the dev console until this user's
|
||||
password is changed. Please login to this user and change the password as
|
||||
your first step.
|
||||
|
||||
<br/>
|
||||
|
||||
## License
|
||||
|
||||
This repository is licensed under AGPL-3.0; However, our SDK (puter.js) is also available under Apache 2.0, as indicated by the license file in that section (packages/puter-js) of this repository.
|
||||
|
||||
<br/>
|
||||
|
||||
## FAQ
|
||||
|
||||
### ❓ What's the use case for Puter?
|
||||
@@ -88,12 +154,16 @@ Puter interacts directly with the DOM and jQuery provides an elegant yet powerfu
|
||||
## #DoesItRunPuter
|
||||
|
||||
- [Minecraft](https://twitter.com/HeyPuter/status/1771957571496092036) | [video](https://www.youtube.com/watch?v=GIowZUXkg5g)
|
||||
- [Samsung Watch](https://twitter.com/CharmunkDev/status/1781501714543030554)
|
||||
- [PlayStation 4](https://twitter.com/HeyPuter/status/1767978053014270059)
|
||||
- [Skyworth TV](https://twitter.com/ericalexdube/status/1767983049277411564)
|
||||
- [A Fridge!](https://twitter.com/HeyPuter/status/1778890003797745842)
|
||||
- [Oculus Quest 2](https://twitter.com/HeyPuter/status/1768664081756754012)
|
||||
- [Tesla Model 3](https://twitter.com/EricLighthall/status/1781479732997214501)
|
||||
- [Tesla Model S](https://twitter.com/HeyPuter/status/1767971178864587057)
|
||||
- [Tesla Model Y](https://twitter.com/HeyPuter/status/1772858333751636310)
|
||||
- Tesla Model 3
|
||||
- [Nintendo Switch](https://twitter.com/HeyPuter/status/1780645795240538518)
|
||||
- [Steam Deck](https://twitter.com/everythingSung/status/1782162352403828793)
|
||||
|
||||
<br/>
|
||||
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
# Configurating Domains for Self-Hosted Puter
|
||||
|
||||
## Local Network Configuration
|
||||
|
||||
### Prerequisite Conditions
|
||||
|
||||
Ensure the hosting device has a static IP address to prevent potential connectivity issues due to IP changes. This setup will enable seamless access to Puter and its services across your local network.
|
||||
|
||||
### Using Hosts Files
|
||||
|
||||
The hosts file is a straightforward way to map domain names to IP addresses on individual devices. It's simple to set up but requires manual changes on each device that needs access to the domains.
|
||||
|
||||
#### Windows
|
||||
1. Open Notepad as an administrator.
|
||||
2. Open the file located at `C:\Windows\System32\drivers\etc\hosts`.
|
||||
3. Add lines for your domain and subdomain with the server's IP address, in the
|
||||
following format:
|
||||
```
|
||||
192.168.1.10 puter.local
|
||||
192.168.1.10 api.puter.local
|
||||
```
|
||||
|
||||
#### For macOS and Linux:
|
||||
1. Open a terminal.
|
||||
2. Edit the hosts file with a text editor, e.g., `sudo nano /etc/hosts`.
|
||||
3. Add lines for your domain and subdomain with the server's IP address, in the
|
||||
following format:
|
||||
```
|
||||
192.168.1.10 puter.local
|
||||
192.168.1.10 api.puter.local
|
||||
```
|
||||
4. Save and exit the editor.
|
||||
|
||||
|
||||
### Using Router Configuration
|
||||
|
||||
Some routers allow you to add custom DNS rules, letting you configure domain names network-wide without touching each device.
|
||||
|
||||
1. Access your router’s admin interface (usually through a web browser).
|
||||
2. Look for DNS or DHCP settings.
|
||||
3. Add custom DNS mappings for `puter.local` and `api.puter.local` to the hosting device's IP address.
|
||||
4. Save the changes and reboot the router if necessary.
|
||||
|
||||
This method's availability and steps may vary depending on your router's model and firmware.
|
||||
|
||||
### Using Local DNS
|
||||
|
||||
Setting up a local DNS server on your network allows for flexible and scalable domain name resolution. This method works across all devices automatically once they're configured to use the DNS server.
|
||||
|
||||
#### Options for DNS Software:
|
||||
|
||||
- **Pi-hole**: Acts as both an ad-blocker and a DNS server. Ideal for easy setup and maintenance.
|
||||
- **BIND9**: Offers comprehensive DNS server capabilities for complex setups.
|
||||
- **Dnsmasq**: Lightweight and suitable for smaller networks or those new to running a DNS server.
|
||||
|
||||
**contributors note:** feel free to add any software you're aware of
|
||||
which might help with this to the list. Also, feel free to add instructions here for specific software; our goal is for Puter to be easy to setup with tools you're already familiar with.
|
||||
|
||||
#### General Steps:
|
||||
|
||||
1. Choose and install DNS server software on a device within your network.
|
||||
2. Configure the DNS server to resolve `puter.local` and `api.puter.local` to the IP address of your Puter hosting device.
|
||||
3. Update your router’s DHCP settings to distribute the DNS server's IP address to all devices on the network.
|
||||
|
||||
By setting up a local DNS server, you gain the most flexibility and control over your network's domain name resolution, ensuring that all devices can access Puter and its API without manual configuration.
|
||||
|
||||
## Production Configuration
|
||||
|
||||
Please note the self-hosting feature is still in alpha and a public production
|
||||
deployment is not recommended at this time. However, if you wish to host
|
||||
publically you can do so following the same steps you normally would to configure
|
||||
a domain name and ensuring the `api` subdomain points to the server as well.
|
||||
@@ -0,0 +1,39 @@
|
||||
## Puter Support Levels for Repository Updates
|
||||
|
||||
This document describes issues requiring repository changes;
|
||||
which issues will be fixed by Puter's core team, and which ones
|
||||
will be fixed if the community makes a contribution.
|
||||
|
||||
This document is not "law". It is provided only as a helpful guide
|
||||
on what to expect.
|
||||
|
||||
### Level Glossary
|
||||
|
||||
| Name | Description |
|
||||
| ---- | ----------- |
|
||||
| Core | Core developers will fix this |
|
||||
| Community | We will accept contributions to fix this |
|
||||
| Mixed | Core developers will fix this if it's currently a priority |
|
||||
|
||||
### Issues and their Levels
|
||||
|
||||
| Issue | Priority |
|
||||
| ----- | -------- |
|
||||
| Security vulnerability | Core |
|
||||
| Breaking change to SDK or API | Core |
|
||||
| Bug in service in CoreModule | Core |
|
||||
| Bug in a built-in app | Core |
|
||||
| Login/init failure in Docker on `release` branch | Core |
|
||||
| Login/init failure in Linux or OSX | Core |
|
||||
| Login/init failure in Docker on `main` branch | Mixed |
|
||||
| Login/init failure with specific configuration | Mixed |
|
||||
| Login/init failure in Windows | Community |
|
||||
|
||||
|
||||
## Puter Support for a Particular Deployment
|
||||
|
||||
If you experience issues on a self-hosted deployment we're here to
|
||||
help. Some issues are related to configuration or environment, so
|
||||
we may only be able to help in a limited capacity. Issues related
|
||||
to data loss, data corruption, or security will have higher priority
|
||||
over other issues with particular deployments.
|
||||
+23
-5
@@ -1,7 +1,25 @@
|
||||
version: '3'
|
||||
|
||||
---
|
||||
version: "3.8"
|
||||
services:
|
||||
app:
|
||||
build: ./
|
||||
puter:
|
||||
container_name: puter
|
||||
image: ghcr.io/heyputer/puter:latest
|
||||
pull_policy: always
|
||||
# build: ./
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- 4000:4000
|
||||
- '4100:4100'
|
||||
environment:
|
||||
# TZ: Europe/Paris
|
||||
# CONFIG_PATH: /etc/puter
|
||||
PUID: 1000
|
||||
PGID: 1000
|
||||
volumes:
|
||||
- ./puter/config:/etc/puter
|
||||
- ./puter/data:/var/puter
|
||||
healthcheck:
|
||||
test: wget --no-verbose --tries=1 --spider http://puter.localhost:4100/test || exit 1
|
||||
interval: 30s
|
||||
timeout: 3s
|
||||
retries: 3
|
||||
start_period: 30s
|
||||
Generated
+1035
-18
File diff suppressed because it is too large.
Load diff
+4
-3
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "puter.com",
|
||||
"version": "1.0.0",
|
||||
"version": "2.2.0",
|
||||
"author": "Puter Technologies Inc.",
|
||||
"license": "AGPL-3.0-only",
|
||||
"description": "Desktop environment in the browser!",
|
||||
@@ -22,11 +22,12 @@
|
||||
"webpack-cli": "^5.1.1"
|
||||
},
|
||||
"scripts": {
|
||||
"test": "echo \"Error: no test specified\" && exit 1",
|
||||
"test": "mocha ./packages/phoenix/test ./packages/phoenix/packages/contextlink/test",
|
||||
"start=gui": "nodemon --exec \"node dev-server.js\" ",
|
||||
"start": "node run-selfhosted.js",
|
||||
"build": "node ./build.js",
|
||||
"check-translations": "node tools/check-translations.js"
|
||||
"check-translations": "node tools/check-translations.js",
|
||||
"postinstall": "cd packages/phoenix && cd packages/contextlink && npm install && cd - && cd packages/strataparse && npm install && cd - && cd packages/pty && npm install"
|
||||
},
|
||||
"workspaces": [
|
||||
"packages/*"
|
||||
|
||||
@@ -18,8 +18,9 @@
|
||||
*/
|
||||
const CoreModule = require("./src/CoreModule.js");
|
||||
const { Kernel } = require("./src/Kernel.js");
|
||||
const LocalDiskStorageModule = require("./src/LocalDiskStorageModule.js");
|
||||
const DatabaseModule = require("./src/DatabaseModule.js");
|
||||
const LocalDiskStorageModule = require("./src/LocalDiskStorageModule.js");
|
||||
const SelfhostedModule = require("./src/SelfhostedModule.js");
|
||||
const PuterDriversModule = require("./src/PuterDriversModule.js");
|
||||
const { testlaunch } = require("./src/index.js");
|
||||
const BaseService = require("./src/services/BaseService.js");
|
||||
@@ -44,4 +45,5 @@ module.exports = {
|
||||
DatabaseModule,
|
||||
PuterDriversModule,
|
||||
LocalDiskStorageModule,
|
||||
SelfhostedModule,
|
||||
};
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@heyputer/backend",
|
||||
"version": "1.0.0",
|
||||
"version": "2.1.0",
|
||||
"description": "Backend/Kernel for Puter",
|
||||
"main": "exports.js",
|
||||
"scripts": {
|
||||
|
||||
@@ -43,6 +43,11 @@ module.exports = CoreModule;
|
||||
const install = async ({ services, app }) => {
|
||||
const config = require('./config');
|
||||
|
||||
// /!\ IMPORTANT /!\
|
||||
// For new services, put the import immediate above the
|
||||
// call to services.registerService. We'll clean this up
|
||||
// in a future PR.
|
||||
|
||||
const { LogService } = require('./services/runtime-analysis/LogService');
|
||||
const { PagerService } = require('./services/runtime-analysis/PagerService');
|
||||
const { AlarmService } = require('./services/runtime-analysis/AlarmService');
|
||||
@@ -182,9 +187,11 @@ const install = async ({ services, app }) => {
|
||||
const { EventService } = require('./services/EventService');
|
||||
services.registerService('event', EventService);
|
||||
|
||||
const DefaultUserService = require('./services/DefaultUserService');
|
||||
services.registerService('__default-user', DefaultUserService);
|
||||
const { PuterVersionService } = require('./services/PuterVersionService');
|
||||
services.registerService('puter-version', PuterVersionService);
|
||||
|
||||
const { SessionService } = require('./services/SessionService');
|
||||
services.registerService('session', SessionService);
|
||||
}
|
||||
|
||||
const install_legacy = async ({ services }) => {
|
||||
@@ -195,7 +202,6 @@ const install_legacy = async ({ services }) => {
|
||||
const PerformanceMonitor = require('./monitor/PerformanceMonitor');
|
||||
const { OperationTraceService } = require('./services/OperationTraceService');
|
||||
const { WSPushService } = require('./services/WSPushService');
|
||||
const { PuterVersionService } = require('./services/PuterVersionService');
|
||||
const { ReferralCodeService } = require('./services/ReferralCodeService');
|
||||
const { Emailservice } = require('./services/EmailService');
|
||||
const { ClientOperationService } = require('./services/ClientOperationService');
|
||||
@@ -210,7 +216,6 @@ const install_legacy = async ({ services }) => {
|
||||
services.registerService('filesystem', FilesystemService);
|
||||
services.registerService('operationTrace', OperationTraceService);
|
||||
services.registerService('__event-push-ws', WSPushService);
|
||||
services.registerService('puter-version', PuterVersionService);
|
||||
services.registerService('referral-code', ReferralCodeService);
|
||||
services.registerService('email', Emailservice);
|
||||
services.registerService('file-cache', FileCacheService);
|
||||
|
||||
@@ -95,11 +95,8 @@ class Kernel extends AdvancedBase {
|
||||
|
||||
root_context.arun(async () => {
|
||||
await this._install_modules();
|
||||
});
|
||||
|
||||
(async () => {
|
||||
await this._boot_services();
|
||||
})();
|
||||
});
|
||||
|
||||
|
||||
// Error.stackTraceLimit = Infinity;
|
||||
|
||||
@@ -23,6 +23,9 @@ class LocalDiskStorageModule extends AdvancedBase {
|
||||
const services = context.get('services');
|
||||
const LocalDiskStorageService = require("./services/LocalDiskStorageService");
|
||||
services.registerService('local-disk-storage', LocalDiskStorageService);
|
||||
|
||||
const HostDiskUsageService = require('./services/HostDiskUsageService');
|
||||
services.registerService('host-disk-usage', HostDiskUsageService);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
const { AdvancedBase } = require("puter-js-common");
|
||||
const config = require("./config");
|
||||
|
||||
class SelfhostedModule extends AdvancedBase {
|
||||
async install (context) {
|
||||
const services = context.get('services');
|
||||
|
||||
const DefaultUserService = require('./services/DefaultUserService');
|
||||
services.registerService('__default-user', DefaultUserService);
|
||||
|
||||
const ComplainAboutVersionsService = require('./services/ComplainAboutVersionsService');
|
||||
services.registerService('complain-about-versions', ComplainAboutVersionsService);
|
||||
|
||||
const DevWatcherService = require('./services/DevWatcherService');
|
||||
const path_ = require('path');
|
||||
services.registerService('__dev-watcher', DevWatcherService, {
|
||||
root: path_.resolve(__dirname, '../../../'),
|
||||
commands: [
|
||||
{
|
||||
name: 'puter.js:webpack-watch',
|
||||
directory: 'packages/puter-js',
|
||||
command: 'npm',
|
||||
args: ['run', 'start-webpack'],
|
||||
},
|
||||
{
|
||||
name: 'terminal:rollup-watch',
|
||||
directory: 'packages/terminal',
|
||||
command: 'npx',
|
||||
args: ['rollup', '-c', 'rollup.config.js', '--watch'],
|
||||
env: {
|
||||
PUTER_JS_URL: ({ global_config: config }) => config.origin + '/sdk/puter.dev.js',
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'phoenix:rollup-watch',
|
||||
directory: 'packages/phoenix',
|
||||
command: 'npx',
|
||||
args: ['rollup', '-c', 'rollup.config.js', '--watch'],
|
||||
env: {
|
||||
PUTER_JS_URL: ({ global_config: config }) => config.origin + '/sdk/puter.dev.js',
|
||||
}
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const ServeStaticFilesService = require("./services/ServceStaticFilesService");
|
||||
services.registerService('__serve-puterjs', ServeStaticFilesService, {
|
||||
directories: [
|
||||
{
|
||||
prefix: '/sdk',
|
||||
path: path_.resolve(__dirname, '../../../packages/puter-js/dist'),
|
||||
},
|
||||
{
|
||||
prefix: '/builtin/terminal',
|
||||
path: path_.resolve(__dirname, '../../../packages/terminal/dist'),
|
||||
},
|
||||
{
|
||||
prefix: '/builtin/phoenix',
|
||||
path: path_.resolve(__dirname, '../../../packages/phoenix/dist'),
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = SelfhostedModule;
|
||||
@@ -128,6 +128,10 @@ module.exports = class APIError {
|
||||
return `Invalid id`;
|
||||
}
|
||||
},
|
||||
'invalid_operation': {
|
||||
status: 400,
|
||||
message: ({ operation }) => `Invalid operation: ${quot(operation)}.`,
|
||||
},
|
||||
'field_invalid': {
|
||||
status: 400,
|
||||
message: ({ key, expected, got }) => {
|
||||
|
||||
@@ -109,7 +109,7 @@ class Sequence {
|
||||
async run (values) {
|
||||
// Initialize scope
|
||||
values = values || this.thisArg?.values || {};
|
||||
Object.assign(this.scope_, values);
|
||||
Object.assign(this.scope_, values); // TODO: can this be __proto__?
|
||||
|
||||
// Run sequence
|
||||
for ( ; this.i < this.steps.length ; this.i++ ) {
|
||||
|
||||
@@ -53,6 +53,11 @@ config.max_subdomains_per_user = 2000;
|
||||
config.storage_capacity = 1*1024*1024*1024;
|
||||
config.static_hosting_domain = '-static.puter.local';
|
||||
|
||||
// Storage limiting is set to false by default
|
||||
// Storage available on the mountpoint/drive puter is running is the storage available
|
||||
config.is_storage_limited = false;
|
||||
config.available_device_storage = null;
|
||||
|
||||
config.thumb_width = 80;
|
||||
config.thumb_height = 80;
|
||||
config.app_max_icon_size = 5*1024*1024;
|
||||
@@ -92,6 +97,10 @@ if (config.server_id) {
|
||||
|
||||
config.contact_email = 'hey@' + config.domain;
|
||||
|
||||
// TODO: default value will be changed to false in a future release;
|
||||
// details to follow in a future announcement.
|
||||
config.legacy_token_migrate = true;
|
||||
|
||||
module.exports = config;
|
||||
|
||||
// NEW_CONFIG_LOADING
|
||||
@@ -100,7 +109,9 @@ const computed_defaults = {
|
||||
pub_port: config => config.http_port,
|
||||
origin: config => config.protocol + '://' + config.domain +
|
||||
(config.pub_port !== 80 && config.pub_port !== 443 ? ':' + config.pub_port : ''),
|
||||
api_base_url: config => config.protocol + '://api.' + config.domain +
|
||||
api_base_url: config => config.experimental_no_subdomain
|
||||
? config.origin
|
||||
: config.protocol + '://api.' + config.domain +
|
||||
(config.pub_port !== 80 && config.pub_port !== 443 ? ':' + config.pub_port : ''),
|
||||
social_card: config => `${config.origin}/assets/img/screenshot.png`,
|
||||
};
|
||||
|
||||
@@ -387,21 +387,9 @@ module.exports = class FSNodeContext {
|
||||
* @deprecated sharing will use user-to-user permissions
|
||||
*/
|
||||
async fetchShares (force) {
|
||||
if ( this.entry.permissions && ! force ) return;
|
||||
|
||||
const db = this.services.get('database').get(DB_READ, 'filesystem');
|
||||
|
||||
let shares = await db.read(
|
||||
`SELECT share.id as share_id, user.* FROM share
|
||||
INNER JOIN user ON share.recipient_user_id = user.id
|
||||
WHERE share.fsentry_id = ?`,
|
||||
[this.entry.id]
|
||||
);
|
||||
const shares_tidy = [];
|
||||
for ( const share of shares ) {
|
||||
shares_tidy.push({uid: share.share_id, username: share.username, email: share.email});
|
||||
}
|
||||
this.entry.permissions = shares_tidy;
|
||||
// NOOP: this was for legacy sharing functionality;
|
||||
// this is being re-implemented with permissions
|
||||
return;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -34,8 +34,10 @@ const APIError = require('../api/APIError.js');
|
||||
const { LLMkdir } = require('./ll_operations/ll_mkdir.js');
|
||||
const { LLCWrite, LLOWrite } = require('./ll_operations/ll_write.js');
|
||||
const { LLCopy } = require('./ll_operations/ll_copy.js');
|
||||
const { PermissionUtil, PermissionRewriter } = require('../services/auth/PermissionService.js');
|
||||
const { PermissionUtil, PermissionRewriter, PermissionImplicator } = require('../services/auth/PermissionService.js');
|
||||
const { DB_WRITE } = require("../services/database/consts");
|
||||
const { UserActorType } = require('../services/auth/Actor');
|
||||
const { get_user } = require('../helpers');
|
||||
|
||||
class FilesystemService extends AdvancedBase {
|
||||
static MODULES = {
|
||||
@@ -131,6 +133,39 @@ class FilesystemService extends AdvancedBase {
|
||||
return `fs:${uid}:${rest.join(':')}`;
|
||||
},
|
||||
}));
|
||||
svc_permission.register_implicator(PermissionImplicator.create({
|
||||
matcher: permission => {
|
||||
return permission.startsWith('fs:');
|
||||
},
|
||||
checker: async (actor, permission) => {
|
||||
debugger;
|
||||
if ( !(actor.type instanceof UserActorType) ) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const [_, uid] = PermissionUtil.split(permission);
|
||||
const node = await this.node(new NodeUIDSelector(uid));
|
||||
|
||||
if ( ! await node.exists() ) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const owner_id = await node.get('user_id');
|
||||
|
||||
// These conditions should never happen
|
||||
if ( ! owner_id || ! actor.type.user.id ) {
|
||||
throw new Error(
|
||||
'something unexpected happened'
|
||||
);
|
||||
}
|
||||
|
||||
if ( owner_id === actor.type.user.id ) {
|
||||
return {};
|
||||
}
|
||||
|
||||
return undefined;
|
||||
},
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -85,6 +85,12 @@ class BatchExecutor extends AdvancedBase {
|
||||
if ( ! x ) throw new Error('no context');
|
||||
|
||||
try {
|
||||
if ( ! command_cls ) {
|
||||
throw APIError.create('invalid_operation', null, {
|
||||
operation: op.op,
|
||||
});
|
||||
}
|
||||
|
||||
if ( file ) workUnit.checkpoint(
|
||||
'about to run << ' +
|
||||
(file.originalname ?? file.name) +
|
||||
|
||||
@@ -23,6 +23,7 @@ const { NodePathSelector, RootNodeSelector } = require("../node/selectors");
|
||||
const { HLFilesystemOperation } = require("./definitions");
|
||||
const { MkTree } = require("./hl_mkdir");
|
||||
const { HLRemove } = require("./hl_remove");
|
||||
const config = require("../../config");
|
||||
|
||||
class HLCopy extends HLFilesystemOperation {
|
||||
static DESCRIPTION = `
|
||||
@@ -141,7 +142,7 @@ class HLCopy extends HLFilesystemOperation {
|
||||
let deset_usage = await sizeService.get_usage(dest_user.id);
|
||||
|
||||
const size = await source.fetchSize(values.user);
|
||||
let capacity = (dest_user.free_storage === undefined || dest_user.free_storage === null) ? config.storage_capacity : dest_user.free_storage
|
||||
let capacity = config.is_storage_limited ? (dest_user.free_storage === undefined || dest_user.free_storage === null) ? config.storage_capacity : dest_user.free_storage : config.available_device_storage
|
||||
if(capacity - deset_usage - size < 0){
|
||||
throw APIError.create('storage_limit_reached');
|
||||
}
|
||||
@@ -162,6 +163,7 @@ class HLCopy extends HLFilesystemOperation {
|
||||
throw APIError('cannot_copy_item_into_itself');
|
||||
}
|
||||
|
||||
let overwritten;
|
||||
if ( await dest.exists() ) {
|
||||
// condition: no overwrite behaviour specified
|
||||
if ( ! values.overwrite && ! values.dedupe_name ) {
|
||||
@@ -188,12 +190,13 @@ class HLCopy extends HLFilesystemOperation {
|
||||
dest = await parent.getChild(target_name);
|
||||
}
|
||||
else if ( values.overwrite ) {
|
||||
if ( ! await chkperm(dest.entry, options.user.id, 'rm') ) {
|
||||
if ( ! await chkperm(dest.entry, values.user.id, 'rm') ) {
|
||||
throw APIError.create('forbidden');
|
||||
}
|
||||
|
||||
// TODO: This will be LLRemove
|
||||
// TODO: what to do with parent_operation?
|
||||
overwritten = await dest.getSafeEntry();
|
||||
const hl_remove = new HLRemove();
|
||||
await hl_remove.run({
|
||||
target: dest,
|
||||
@@ -212,7 +215,10 @@ class HLCopy extends HLFilesystemOperation {
|
||||
|
||||
await this.copied.awaitStableEntry();
|
||||
const response = await this.copied.getSafeEntry({ thumbnail: true });
|
||||
return response;
|
||||
return {
|
||||
copied : response,
|
||||
overwritten
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -24,6 +24,7 @@ const { HLFilesystemOperation } = require("./definitions");
|
||||
const { MkTree } = require("./hl_mkdir");
|
||||
const { HLRemove } = require("./hl_remove");
|
||||
const { TYPE_DIRECTORY } = require("../FSNodeContext");
|
||||
const config = require("../../config");
|
||||
|
||||
class HLMove extends HLFilesystemOperation {
|
||||
static MODULES = {
|
||||
@@ -105,7 +106,7 @@ class HLMove extends HLFilesystemOperation {
|
||||
dest_user = source_user;
|
||||
await source.fetchSize();
|
||||
const item_size = source.entry.size;
|
||||
let capacity = (dest_user.free_storage === undefined || dest_user.free_storage === null) ? config.storage_capacity : dest_user.free_storage
|
||||
let capacity = config.is_storage_limited ? (dest_user.free_storage === undefined || dest_user.free_storage === null) ? config.storage_capacity : dest_user.free_storage : config.available_device_storage;
|
||||
if(capacity - await df(dest_user.id) - item_size < 0){
|
||||
throw APIError.create('storage_limit_reached');
|
||||
}
|
||||
|
||||
@@ -24,7 +24,7 @@ const { HLFilesystemOperation } = require("./definitions");
|
||||
|
||||
class HLReadDir extends HLFilesystemOperation {
|
||||
async _run () {
|
||||
const { subject, user, no_thumbs, no_assocs } = this.values;
|
||||
const { subject, user, no_thumbs, no_assocs, actor } = this.values;
|
||||
|
||||
if ( ! await subject.exists() ) {
|
||||
throw APIError.create('subject_does_not_exist');
|
||||
@@ -49,12 +49,12 @@ class HLReadDir extends HLFilesystemOperation {
|
||||
await child.fetchSubdomains(user);
|
||||
}
|
||||
const fs = require('fs');
|
||||
fs.appendFileSync('/tmp/children.log',
|
||||
JSON.stringify({
|
||||
no_thumbs,
|
||||
no_assocs,
|
||||
entry: child.entry,
|
||||
}) + '\n');
|
||||
// fs.appendFileSync('/tmp/children.log',
|
||||
// JSON.stringify({
|
||||
// no_thumbs,
|
||||
// no_assocs,
|
||||
// entry: child.entry,
|
||||
// }) + '\n');
|
||||
return await child.getSafeEntry({ thumbnail: ! no_thumbs });
|
||||
}));
|
||||
}
|
||||
|
||||
@@ -45,7 +45,7 @@ class HLStat extends HLFilesystemOperation {
|
||||
const svc_acl = context.get('services').get('acl');
|
||||
const actor = context.get('actor');
|
||||
if ( ! await svc_acl.check(actor, subject, 'read') ) {
|
||||
throw await svc_acl.get_safe_acl_error(actor, subject.entry, 'read');
|
||||
throw await svc_acl.get_safe_acl_error(actor, subject, 'read');
|
||||
}
|
||||
|
||||
// check permission
|
||||
|
||||
@@ -61,8 +61,8 @@ class WriteCommonTrait {
|
||||
const { file, user } = this.values;
|
||||
|
||||
const usage = await sizeService.get_usage(user.id);
|
||||
let capacity = user.free_storage == undefined
|
||||
? config.storage_capacity : user.free_storage;
|
||||
let capacity = config.is_storage_limited ? user.free_storage == undefined
|
||||
? config.storage_capacity : user.free_storage : config.available_device_storage;
|
||||
if( capacity - usage - file.size < 0 ) {
|
||||
throw APIError.create('storage_limit_reached');
|
||||
}
|
||||
|
||||
@@ -17,9 +17,8 @@
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
const APIError = require("../../api/APIError");
|
||||
const { chkperm, get_descendants } = require("../../helpers");
|
||||
const { TYPE_DIRECTORY } = require("../FSNodeContext");
|
||||
const { NodeUIDSelector, NodeRawEntrySelector } = require("../node/selectors");
|
||||
const { RootNodeSelector } = require("../node/selectors");
|
||||
const { NodeUIDSelector, NodeChildSelector } = require("../node/selectors");
|
||||
const { LLFilesystemOperation } = require("./definitions");
|
||||
|
||||
class LLReadDir extends LLFilesystemOperation {
|
||||
@@ -42,27 +41,14 @@ class LLReadDir extends LLFilesystemOperation {
|
||||
const svc_fsentry = svc.get('fsEntryService');
|
||||
const svc_fs = svc.get('filesystem');
|
||||
|
||||
if (
|
||||
subject.isRoot ||
|
||||
(await subject.isUserDirectory() && subject.name !== user.username)
|
||||
) {
|
||||
this.checkpoint('before call to get_descendants')
|
||||
const entries = await get_descendants(
|
||||
await subject.get('path'),
|
||||
user,
|
||||
1, true,
|
||||
)
|
||||
this.checkpoint('after call to get_descendants')
|
||||
|
||||
const children = await Promise.all(entries.map(async entry => {
|
||||
const node = await svc_fs.node(new NodeRawEntrySelector(entry));
|
||||
node.found_thumbnail = false;
|
||||
return node;
|
||||
}))
|
||||
|
||||
this.checkpoint('after get children (2)');
|
||||
|
||||
return children;
|
||||
if ( subject.isRoot ) {
|
||||
if ( ! actor.type.user ) return [];
|
||||
return [
|
||||
await svc_fs.node(new NodeChildSelector(
|
||||
new RootNodeSelector(),
|
||||
actor.type.user.username,
|
||||
))
|
||||
];
|
||||
}
|
||||
|
||||
this.checkpoint('before get direct descendants')
|
||||
|
||||
@@ -1128,6 +1128,7 @@ async function deleteUser(user_id){
|
||||
}
|
||||
|
||||
function subdomain(req){
|
||||
if ( config.experimental_no_subdomain ) return 'api';
|
||||
return req.hostname.slice(0, -1 * (config.domain.length + 1));
|
||||
}
|
||||
|
||||
@@ -1146,7 +1147,7 @@ async function jwt_auth(req){
|
||||
else if(req.handshake && req.handshake.query && req.handshake.query.auth_token)
|
||||
token = req.handshake.query.auth_token;
|
||||
|
||||
if(!token)
|
||||
if(!token || token === 'null')
|
||||
throw('No auth token found');
|
||||
else if (typeof token !== 'string')
|
||||
throw('token must be a string.')
|
||||
@@ -1154,34 +1155,22 @@ async function jwt_auth(req){
|
||||
token = token.replace('Bearer ', '')
|
||||
|
||||
try{
|
||||
const jwt = require('jsonwebtoken');
|
||||
const decoded = jwt.verify(token, config.jwt_secret)
|
||||
const svc_auth = Context.get('services').get('auth');
|
||||
const actor = await svc_auth.authenticate_from_token(token);
|
||||
|
||||
if ( decoded.type ) {
|
||||
// This is usually not the correct way to throw an APIError;
|
||||
// this is a workaround for the existing error handling in auth,
|
||||
// which is well tested, stable, and legacy (no sense in refactoring)
|
||||
if ( ! actor.type?.constructor?.name === 'UserActorType' ) {
|
||||
throw({
|
||||
message: APIError.create('token_unsupported')
|
||||
.serialize(),
|
||||
});
|
||||
}
|
||||
|
||||
/** @type BaseDatabaseAccessService */
|
||||
const db = services.get('database').get(DB_READ, 'filesystem');
|
||||
|
||||
// in the vast majority of cases looking up a user should succeed unless the request is invalid (rare case),
|
||||
// that's why we first hit up the read replica and if not successful we try the master DB
|
||||
let user = await db.requireRead('SELECT * FROM `user` WHERE `uuid` = ? LIMIT 1', [decoded.uuid]);
|
||||
|
||||
// unsuccessful
|
||||
if(!user[0])
|
||||
throw('');
|
||||
// successful
|
||||
else {
|
||||
return {user: user[0], token: token};
|
||||
}
|
||||
return {
|
||||
user: actor.type.user,
|
||||
token: token,
|
||||
};
|
||||
}catch(e){
|
||||
console.log('ERROR', e);
|
||||
throw(e.message);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,35 +17,26 @@
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
"use strict"
|
||||
const APIError = require('../api/APIError');
|
||||
const {jwt_auth} = require('../helpers');
|
||||
const { UserActorType } = require('../services/auth/Actor');
|
||||
const { DB_WRITE } = require('../services/database/consts');
|
||||
const { Context } = require('../util/context');
|
||||
const auth2 = require('./auth2');
|
||||
|
||||
const auth = async (req, res, next)=>{
|
||||
let auth2_ok = false;
|
||||
try{
|
||||
let auth_res = await jwt_auth(req);
|
||||
// Delegate to new middleware
|
||||
await auth2(req, res, () => { auth2_ok = true; });
|
||||
if ( ! auth2_ok ) return;
|
||||
|
||||
// is account suspended?
|
||||
if(auth_res.user.suspended)
|
||||
return res.status(401).send({error: 'Account suspended'});
|
||||
|
||||
// successful auth
|
||||
req.user = auth_res.user;
|
||||
req.token = auth_res.token;
|
||||
|
||||
// let's add it to the context too
|
||||
try {
|
||||
const x = Context.get();
|
||||
x.set('user', req.user);
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
// Everything using the old reference to the auth middleware
|
||||
// should only allow session tokens
|
||||
if ( ! (req.actor.type instanceof UserActorType) ) {
|
||||
throw APIError.create('forbidden');
|
||||
}
|
||||
|
||||
// record as daily active users
|
||||
const db = req.services.get('database').get(DB_WRITE, 'auth');
|
||||
db.write('UPDATE `user` SET `last_activity_ts` = now() WHERE id=? LIMIT 1', [req.user.id]);
|
||||
|
||||
// go to next
|
||||
next();
|
||||
}
|
||||
// auth failed
|
||||
|
||||
@@ -18,8 +18,24 @@
|
||||
*/
|
||||
const APIError = require("../api/APIError");
|
||||
const config = require("../config");
|
||||
const { UserActorType } = require("../services/auth/Actor");
|
||||
const { LegacyTokenError } = require("../services/auth/AuthService");
|
||||
const { Context } = require("../util/context");
|
||||
|
||||
// The "/whoami" endpoint is a special case where we want to allow
|
||||
// a legacy token to be used for authentication. The "/whoami"
|
||||
// endpoint will then return a new token for further requests.
|
||||
//
|
||||
const is_whoami = (req) => {
|
||||
if ( ! config.legacy_token_migrate ) return;
|
||||
|
||||
if ( req.path !== '/whoami' ) return;
|
||||
|
||||
// const subdomain = req.subdomains[res.subdomains.length - 1];
|
||||
// if ( subdomain !== 'api' ) return;
|
||||
return true;
|
||||
}
|
||||
|
||||
// TODO: Allow auth middleware to be used without requiring
|
||||
// authentication. This will allow us to use the auth middleware
|
||||
// in endpoints that do not require authentication, but can
|
||||
@@ -47,8 +63,10 @@ const auth2 = async (req, res, next) => {
|
||||
|
||||
if(!token) {
|
||||
APIError.create('token_missing').write(res);
|
||||
return;
|
||||
} else if (typeof token !== 'string') {
|
||||
APIError.create('token_auth_failed').write(res);
|
||||
return;
|
||||
} else {
|
||||
token = token.replace('Bearer ', '')
|
||||
}
|
||||
@@ -70,6 +88,26 @@ const auth2 = async (req, res, next) => {
|
||||
e.write(res);
|
||||
return;
|
||||
}
|
||||
if ( e instanceof LegacyTokenError && is_whoami(req) ) {
|
||||
const new_info = await svc_auth.check_session(token, {
|
||||
req,
|
||||
from_upgrade: true,
|
||||
})
|
||||
context.set('actor', new_info.actor);
|
||||
context.set('user', new_info.user);
|
||||
req.new_token = new_info.token;
|
||||
req.token = new_info.token;
|
||||
req.user = new_info.user;
|
||||
req.actor = new_info.actor;
|
||||
|
||||
res.cookie(config.cookie_name, new_info.token, {
|
||||
sameSite: 'none',
|
||||
secure: true,
|
||||
httpOnly: true,
|
||||
});
|
||||
next();
|
||||
return;
|
||||
}
|
||||
const re = APIError.create('token_auth_failed');
|
||||
re.write(res);
|
||||
return;
|
||||
|
||||
@@ -187,7 +187,10 @@ class AppES extends BaseES {
|
||||
const subdomain = await entity.get('subdomain');
|
||||
const user = Context.get('user');
|
||||
let subdomain_res = await this.db.write(
|
||||
`INSERT IGNORE INTO subdomains
|
||||
`INSERT ${this.db.case({
|
||||
mysql: 'IGNORE',
|
||||
sqlite: 'OR IGNORE',
|
||||
})} INTO subdomains
|
||||
(subdomain, user_id, root_dir_id, uuid) VALUES
|
||||
( ?, ?, ?, ?)`,
|
||||
[
|
||||
|
||||
@@ -94,7 +94,7 @@ class SQLES extends BaseES {
|
||||
}
|
||||
|
||||
const values = [];
|
||||
if ( predicate ) values.push(...predicate.values);
|
||||
if ( predicate ) values.push(...(predicate.values || []));
|
||||
|
||||
if ( this.debug ) {
|
||||
this.log.info('-> SQL STMT', { stmt, values });
|
||||
@@ -219,7 +219,7 @@ class SQLES extends BaseES {
|
||||
console.log('SQL STMT', stmt);
|
||||
console.log('SQL VALS', execute_vals);
|
||||
|
||||
const res = await db.write(
|
||||
const res = await this.db.write(
|
||||
stmt, execute_vals
|
||||
);
|
||||
|
||||
|
||||
@@ -51,6 +51,7 @@ module.exports = {
|
||||
maxlen: 7000,
|
||||
},
|
||||
maximize_on_start: 'flag',
|
||||
background: 'flag',
|
||||
subdomain: {
|
||||
type: 'string',
|
||||
transient: true,
|
||||
|
||||
@@ -176,7 +176,7 @@ router.all('*', async function(req, res, next) {
|
||||
const user = await get_user({uuid: req.query.user_uuid})
|
||||
|
||||
// more validation
|
||||
if(user === undefined || user === null || user === false)
|
||||
if(!user)
|
||||
h += '<p style="text-align:center; color:red;">User not found.</p>';
|
||||
else if(user.unsubscribed === 1)
|
||||
h += '<p style="text-align:center; color:green;">You are already unsubscribed.</p>';
|
||||
@@ -296,8 +296,11 @@ router.all('*', async function(req, res, next) {
|
||||
const APP_ORIGIN = config.origin;
|
||||
const API_ORIGIN = config.api_base_url;
|
||||
return res.send(generate_puter_page_html({
|
||||
env: config.env,
|
||||
|
||||
app_origin: APP_ORIGIN,
|
||||
api_origin: API_ORIGIN,
|
||||
use_bundled_gui: config.use_bundled_gui,
|
||||
|
||||
manifest,
|
||||
gui_path: config.assets.gui,
|
||||
|
||||
@@ -38,7 +38,7 @@ router.get('/apps', auth, express.json({limit: '50mb'}), async (req, res, next)=
|
||||
|
||||
const db = req.services.get('database').get(DB_READ, 'apps');
|
||||
|
||||
let apps_res = await dbrr.read(
|
||||
let apps_res = await db.read(
|
||||
`SELECT * FROM apps WHERE owner_user_id = ? ORDER BY timestamp DESC`,
|
||||
[req.user.id]
|
||||
);
|
||||
@@ -72,6 +72,7 @@ router.get('/apps', auth, express.json({limit: '50mb'}), async (req, res, next)=
|
||||
icon: apps_res[i].icon,
|
||||
index_url: apps_res[i].index_url,
|
||||
godmode: apps_res[i].godmode,
|
||||
background: apps_res[i].background,
|
||||
maximize_on_start: apps_res[i].maximize_on_start,
|
||||
filetype_associations: filetype_associations,
|
||||
...stats,
|
||||
@@ -111,6 +112,7 @@ router.get('/apps/:name', auth, express.json({limit: '50mb'}), async (req, res,
|
||||
title: app.title,
|
||||
icon: app.icon,
|
||||
godmode: app.godmode,
|
||||
background: app.background,
|
||||
maximize_on_start: app.maximize_on_start,
|
||||
index_url: app.index_url,
|
||||
};
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
const eggspress = require("../../api/eggspress");
|
||||
const { deleteUser, invalidate_cached_user } = require("../../helpers");
|
||||
|
||||
const config = require("../../config");
|
||||
|
||||
module.exports = eggspress("/delete-own-user", {
|
||||
subdomain: "api",
|
||||
auth: true,
|
||||
allowedMethods: ["POST"],
|
||||
}, async (req, res, next) => {
|
||||
const bcrypt = require('bcrypt');
|
||||
|
||||
const validate_request = async () => {
|
||||
const user = req.user;
|
||||
|
||||
// `user` should always have a value, but this is checked
|
||||
// any way in case the auth middleware is broken.
|
||||
if ( ! user ) return false;
|
||||
|
||||
// temporary users don't require password verification
|
||||
if ( ! user.email && ! user.password ) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if ( ! req.body.password ) return false;
|
||||
if ( ! user || ! user.password ) return false;
|
||||
if ( ! await bcrypt.compare(req.body.password, req.user.password) ) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
if ( ! await validate_request() ) {
|
||||
return res.status(400).send({ success: false });
|
||||
}
|
||||
|
||||
res.clearCookie(config.cookie_name);
|
||||
|
||||
await deleteUser(req.user.id);
|
||||
invalidate_cached_user(req.user);
|
||||
|
||||
return res.send({ success: true });
|
||||
});
|
||||
@@ -0,0 +1,30 @@
|
||||
const APIError = require("../../api/APIError");
|
||||
const eggspress = require("../../api/eggspress");
|
||||
const { UserActorType } = require("../../services/auth/Actor");
|
||||
const { Context } = require("../../util/context");
|
||||
|
||||
module.exports = eggspress('/auth/grant-user-user', {
|
||||
subdomain: 'api',
|
||||
auth2: true,
|
||||
allowedMethods: ['POST'],
|
||||
}, async (req, res, next) => {
|
||||
const x = Context.get();
|
||||
const svc_permission = x.get('services').get('permission');
|
||||
|
||||
// Only users can grant user-user permissions
|
||||
const actor = Context.get('actor');
|
||||
if ( ! (actor.type instanceof UserActorType) ) {
|
||||
throw APIError.create('forbidden');
|
||||
}
|
||||
|
||||
if ( ! req.body.target_username ) {
|
||||
throw APIError.create('field_missing', null, { key: 'target_username' });
|
||||
}
|
||||
|
||||
await svc_permission.grant_user_user_permission(
|
||||
actor, req.body.target_username, req.body.permission,
|
||||
req.body.extra || {}, req.body.meta || {}
|
||||
);
|
||||
|
||||
res.json({});
|
||||
});
|
||||
@@ -17,7 +17,7 @@
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
const eggspress = require("../../api/eggspress");
|
||||
const { get_app } = require("../../helpers");
|
||||
const { get_app, get_user } = require("../../helpers");
|
||||
const { UserActorType } = require("../../services/auth/Actor");
|
||||
const { DB_READ } = require("../../services/database/consts");
|
||||
const { Context } = require("../../util/context");
|
||||
@@ -38,29 +38,73 @@ module.exports = eggspress('/auth/list-permissions', {
|
||||
|
||||
const db = x.get('services').get('database').get(DB_READ, 'permissions');
|
||||
|
||||
const permissions = [];
|
||||
const permissions = {};
|
||||
|
||||
const rows = await db.read(
|
||||
'SELECT * FROM `user_to_app_permissions` WHERE user_id=?',
|
||||
[ actor.type.user.id ]
|
||||
);
|
||||
{
|
||||
permissions.myself_to_app = [];
|
||||
|
||||
for ( const row of rows ) {
|
||||
const app = await get_app({ id: row.app_id });
|
||||
const rows = await db.read(
|
||||
'SELECT * FROM `user_to_app_permissions` WHERE user_id=?',
|
||||
[ actor.type.user.id ]
|
||||
);
|
||||
|
||||
delete app.id;
|
||||
delete app.approved_for_listing;
|
||||
delete app.approved_for_opening_items;
|
||||
delete app.godmode;
|
||||
delete app.owner_user_id;
|
||||
for ( const row of rows ) {
|
||||
const app = await get_app({ id: row.app_id });
|
||||
|
||||
const permission = {
|
||||
app,
|
||||
permission: row.permission,
|
||||
extra: row.extra
|
||||
};
|
||||
delete app.id;
|
||||
delete app.approved_for_listing;
|
||||
delete app.approved_for_opening_items;
|
||||
delete app.godmode;
|
||||
delete app.owner_user_id;
|
||||
|
||||
permissions.push(permission);
|
||||
const permission = {
|
||||
app,
|
||||
permission: row.permission,
|
||||
extra: row.extra
|
||||
};
|
||||
|
||||
permissions.myself_to_app.push(permission);
|
||||
}
|
||||
}
|
||||
{
|
||||
permissions.myself_to_user = [];
|
||||
|
||||
const rows = await db.read(
|
||||
'SELECT * FROM `user_to_user_permissions` WHERE issuer_user_id=?',
|
||||
[ actor.type.user.id ]
|
||||
);
|
||||
|
||||
for ( const row of rows ) {
|
||||
const user = await get_user({ id: row.holder_user_id });
|
||||
|
||||
const permission = {
|
||||
user: user.username,
|
||||
permission: row.permission,
|
||||
extra: row.extra
|
||||
};
|
||||
|
||||
permissions.myself_to_user.push(permission);
|
||||
}
|
||||
}
|
||||
{
|
||||
permissions.user_to_myself = [];
|
||||
|
||||
const rows = await db.read(
|
||||
'SELECT * FROM `user_to_user_permissions` WHERE holder_user_id=?',
|
||||
[ actor.type.user.id ]
|
||||
);
|
||||
|
||||
for ( const row of rows ) {
|
||||
const user = await get_user({ id: row.issuer_user_id });
|
||||
|
||||
const permission = {
|
||||
user: user.username,
|
||||
permission: row.permission,
|
||||
extra: row.extra
|
||||
};
|
||||
|
||||
permissions.user_to_myself.push(permission);
|
||||
}
|
||||
}
|
||||
|
||||
res.json(permissions);
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
const eggspress = require("../../api/eggspress");
|
||||
const { UserActorType } = require("../../services/auth/Actor");
|
||||
const { Context } = require("../../util/context");
|
||||
|
||||
module.exports = eggspress('/auth/list-sessions', {
|
||||
subdomain: 'api',
|
||||
auth2: true,
|
||||
allowedMethods: ['GET'],
|
||||
}, async (req, res, next) => {
|
||||
const x = Context.get();
|
||||
const svc_auth = x.get('services').get('auth');
|
||||
|
||||
// Only users can list their own sessions
|
||||
// apps, access tokens, etc should NEVER access this
|
||||
const actor = x.get('actor');
|
||||
if ( ! (actor.type instanceof UserActorType) ) {
|
||||
throw APIError.create('forbidden');
|
||||
}
|
||||
|
||||
const sessions = await svc_auth.list_sessions(actor);
|
||||
|
||||
res.json(sessions);
|
||||
});
|
||||
@@ -0,0 +1,33 @@
|
||||
const APIError = require("../../api/APIError");
|
||||
const eggspress = require("../../api/eggspress");
|
||||
const { UserActorType } = require("../../services/auth/Actor");
|
||||
const { Context } = require("../../util/context");
|
||||
|
||||
module.exports = eggspress('/auth/revoke-session', {
|
||||
subdomain: 'api',
|
||||
auth2: true,
|
||||
allowedMethods: ['POST'],
|
||||
}, async (req, res, next) => {
|
||||
const x = Context.get();
|
||||
const svc_auth = x.get('services').get('auth');
|
||||
|
||||
// Only users can list their own sessions
|
||||
// apps, access tokens, etc should NEVER access this
|
||||
const actor = x.get('actor');
|
||||
if ( ! (actor.type instanceof UserActorType) ) {
|
||||
throw APIError.create('forbidden');
|
||||
}
|
||||
|
||||
// Ensure valid UUID
|
||||
if ( ! req.body.uuid || typeof req.body.uuid !== 'string' ) {
|
||||
throw APIError.create('field_invalid', null, {
|
||||
key: 'uuid',
|
||||
expected: 'string'
|
||||
});
|
||||
}
|
||||
|
||||
const sessions = await svc_auth.revoke_session(
|
||||
actor, req.body.uuid);
|
||||
|
||||
res.json({ sessions });
|
||||
});
|
||||
@@ -0,0 +1,31 @@
|
||||
const APIError = require("../../api/APIError");
|
||||
const eggspress = require("../../api/eggspress");
|
||||
const { UserActorType } = require("../../services/auth/Actor");
|
||||
const { Context } = require("../../util/context");
|
||||
|
||||
module.exports = eggspress('/auth/revoke-user-user', {
|
||||
subdomain: 'api',
|
||||
auth2: true,
|
||||
allowedMethods: ['POST'],
|
||||
}, async (req, res, next) => {
|
||||
const x = Context.get();
|
||||
const svc_permission = x.get('services').get('permission');
|
||||
|
||||
// Only users can grant user-user permissions
|
||||
const actor = Context.get('actor');
|
||||
if ( ! (actor.type instanceof UserActorType) ) {
|
||||
throw APIError.create('forbidden');
|
||||
}
|
||||
|
||||
if ( ! req.body.target_username ) {
|
||||
throw APIError.create('field_missing', null, { key: 'target_username' });
|
||||
}
|
||||
|
||||
await svc_permission.revoke_user_user_permission(
|
||||
actor, req.body.target_username, req.body.permission,
|
||||
req.body.meta || {}
|
||||
);
|
||||
|
||||
res.json({});
|
||||
});
|
||||
|
||||
@@ -23,6 +23,11 @@ const eggspress = require('../api/eggspress.js');
|
||||
const APIError = require('../api/APIError.js');
|
||||
const { DB_READ, DB_WRITE } = require('../services/database/consts.js');
|
||||
|
||||
const config = require('../config.js');
|
||||
|
||||
const jwt = require('jsonwebtoken');
|
||||
const { invalidate_cached_user_by_id } = require('../helpers.js');
|
||||
|
||||
const CHANGE_EMAIL_START = eggspress('/change_email/start', {
|
||||
subdomain: 'api',
|
||||
auth: true,
|
||||
@@ -47,7 +52,6 @@ const CHANGE_EMAIL_START = eggspress('/change_email/start', {
|
||||
}
|
||||
|
||||
// check if email is already in use
|
||||
const svc_mysql = req.services.get('mysql');
|
||||
const db = req.services.get('database').get(DB_WRITE, 'auth');
|
||||
const rows = await db.read(
|
||||
'SELECT COUNT(*) AS `count` FROM `user` WHERE `email` = ?',
|
||||
@@ -59,32 +63,42 @@ const CHANGE_EMAIL_START = eggspress('/change_email/start', {
|
||||
|
||||
// generate confirmation token
|
||||
const token = crypto.randomBytes(4).toString('hex');
|
||||
const jwt_token = jwt.sign({
|
||||
user_id: user.id,
|
||||
token,
|
||||
}, config.jwt_secret, { expiresIn: '24h' });
|
||||
|
||||
// send confirmation email
|
||||
const svc_email = req.services.get('email');
|
||||
await svc_email.send_email({ email: new_email }, 'email_change_request', {
|
||||
confirm_url: `${config.origin}/change_email/confirm?token=${jwt_token}`,
|
||||
username: user.username,
|
||||
});
|
||||
|
||||
// update user
|
||||
await db.write(
|
||||
'UPDATE `user` SET `unconfirmed_change_email` = ?, `change_email_confirm_token` = ? WHERE `id` = ?',
|
||||
[new_email, token, user.id]
|
||||
);
|
||||
|
||||
res.send({ success: true });
|
||||
});
|
||||
|
||||
const CHANGE_EMAIL_CONFIRM = eggspress('/change_email/confirm', {
|
||||
subdomain: 'api',
|
||||
auth: true,
|
||||
verified: true,
|
||||
allowedMethods: ['POST'],
|
||||
allowedMethods: ['GET'],
|
||||
}, async (req, res, next) => {
|
||||
const user = req.user;
|
||||
const token = req.body.token;
|
||||
const jwt_token = req.query.token;
|
||||
|
||||
if ( ! token ) {
|
||||
if ( ! jwt_token ) {
|
||||
throw APIError.create('field_missing', null, { key: 'token' });
|
||||
}
|
||||
|
||||
const svc_mysql = req.services.get('mysql');
|
||||
const dbrr = svc_mysql.get(DB_MODE_READ, 'change-email-confirm');
|
||||
const [rows] = await dbrr.promise().query(
|
||||
const { token, user_id } = jwt.verify(jwt_token, config.jwt_secret);
|
||||
|
||||
const db = req.services.get('database').get(DB_WRITE, 'auth');
|
||||
const rows = await db.read(
|
||||
'SELECT `unconfirmed_change_email` FROM `user` WHERE `id` = ? AND `change_email_confirm_token` = ?',
|
||||
[user.id, token]
|
||||
[user_id, token]
|
||||
);
|
||||
if ( rows.length === 0 ) {
|
||||
throw APIError.create('token_invalid');
|
||||
@@ -92,11 +106,19 @@ const CHANGE_EMAIL_CONFIRM = eggspress('/change_email/confirm', {
|
||||
|
||||
const new_email = rows[0].unconfirmed_change_email;
|
||||
|
||||
const db = req.services.get('database').get(DB_WRITE, 'auth');
|
||||
await db.write(
|
||||
'UPDATE `user` SET `email` = ?, `unconfirmed_change_email` = NULL, `change_email_confirm_token` = NULL WHERE `id` = ?',
|
||||
[new_email, user.id]
|
||||
[new_email, user_id]
|
||||
);
|
||||
|
||||
invalidate_cached_user_by_id(user_id);
|
||||
let socketio = require('../socketio.js').getio();
|
||||
if(socketio){
|
||||
socketio.to(user_id).emit('user.email_changed', {})
|
||||
}
|
||||
|
||||
const h = `<p style="text-align:center; color:green;">Your email has been successfully confirmed.</p>`;
|
||||
return res.send(h);
|
||||
});
|
||||
|
||||
module.exports = app => {
|
||||
|
||||
@@ -59,7 +59,11 @@ module.exports = eggspress('/change_username', {
|
||||
// Has the user already changed their username twice this month?
|
||||
const rows = await db.read(
|
||||
'SELECT COUNT(*) AS `count` FROM `user_update_audit` ' +
|
||||
'WHERE `user_id`=? AND `reason`=? AND `created_at` > DATE_SUB(NOW(), INTERVAL 1 MONTH)',
|
||||
'WHERE `user_id`=? AND `reason`=? AND ' +
|
||||
db.case({
|
||||
mysql: '`created_at` > DATE_SUB(NOW(), INTERVAL 1 MONTH)',
|
||||
sqlite: "`created_at` > datetime('now', '-1 month')",
|
||||
}),
|
||||
[ req.user.id, 'change_username' ]
|
||||
);
|
||||
|
||||
|
||||
@@ -21,8 +21,9 @@ const express = require('express');
|
||||
const router = express.Router();
|
||||
const auth = require('../middleware/auth.js');
|
||||
const config = require('../config');
|
||||
const { DB_WRITE } = require('../services/database/consts.js');
|
||||
|
||||
// -----------------------------------------------------------------------//
|
||||
// -----------------------------------------------------------------------//
|
||||
// POST /delete-site
|
||||
// -----------------------------------------------------------------------//
|
||||
router.post('/delete-site', auth, express.json(), async (req, res, next)=>{
|
||||
@@ -40,12 +41,12 @@ router.post('/delete-site', auth, express.json(), async (req, res, next)=>{
|
||||
|
||||
// modules
|
||||
const {} = require('../helpers');
|
||||
const db = require('../db/mysql.js')
|
||||
const db = req.services.get('database').get(DB_WRITE, 'subdomains:legacy');
|
||||
|
||||
await db.promise().execute(
|
||||
`DELETE FROM subdomains WHERE user_id = ? AND uuid = ?`,
|
||||
await db.write(
|
||||
`DELETE FROM subdomains WHERE user_id = ? AND uuid = ?`,
|
||||
[req.user.id, req.body.site_uuid]
|
||||
);
|
||||
);
|
||||
res.send({});
|
||||
})
|
||||
|
||||
|
||||
@@ -22,6 +22,8 @@ const config = require('../config.js');
|
||||
const router = new express.Router();
|
||||
const auth = require('../middleware/auth.js');
|
||||
|
||||
// TODO: Why is this both a POST and a GET?
|
||||
|
||||
// -----------------------------------------------------------------------//
|
||||
// POST /df
|
||||
// -----------------------------------------------------------------------//
|
||||
@@ -35,11 +37,13 @@ router.post('/df', auth, express.json(), async (req, response, next)=>{
|
||||
return response.status(400).send({code: 'account_is_not_verified', message: 'Account is not verified'});
|
||||
|
||||
const {df} = require('../helpers');
|
||||
const svc_hostDiskUsage = req.services.get('host-disk-usage', { optional: true });
|
||||
try{
|
||||
// auth
|
||||
response.send({
|
||||
used: parseInt(await df(req.user.id)),
|
||||
capacity: (req.user.free_storage === undefined || req.user.free_storage === null) ? config.storage_capacity : req.user.free_storage,
|
||||
capacity: config.is_storage_limited ? (req.user.free_storage === undefined || req.user.free_storage === null) ? config.storage_capacity : req.user.free_storage : config.available_device_storage,
|
||||
...(svc_hostDiskUsage ? svc_hostDiskUsage.get_extra() : {}),
|
||||
});
|
||||
}catch(e){
|
||||
console.log(e)
|
||||
@@ -60,11 +64,13 @@ router.get('/df', auth, express.json(), async (req, response, next)=>{
|
||||
return response.status(400).send({code: 'account_is_not_verified', message: 'Account is not verified'});
|
||||
|
||||
const {df} = require('../helpers');
|
||||
const svc_hostDiskUsage = req.services.get('host-disk-usage', { optional: true });
|
||||
try{
|
||||
// auth
|
||||
response.send({
|
||||
used: parseInt(await df(req.user.id)),
|
||||
capacity: (req.user.free_storage === undefined || req.user.free_storage === null) ? config.storage_capacity : req.user.free_storage,
|
||||
capacity: config.is_storage_limited ? (req.user.free_storage === undefined || req.user.free_storage === null) ? config.storage_capacity : req.user.free_storage : config.available_device_storage,
|
||||
...(svc_hostDiskUsage ? svc_hostDiskUsage.get_extra() : {}),
|
||||
});
|
||||
}catch(e){
|
||||
console.log(e)
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
"use strict"
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
const auth = require('../middleware/auth.js');
|
||||
const config = require('../config.js');
|
||||
const fs = require('../middleware/fs.js');
|
||||
const { DB_WRITE } = require('../services/database/consts.js');
|
||||
const { NodePathSelector } = require('../filesystem/node/selectors.js');
|
||||
const { HLRead } = require('../filesystem/hl_operations/hl_read.js');
|
||||
|
||||
// -----------------------------------------------------------------------//
|
||||
// GET /down
|
||||
// -----------------------------------------------------------------------//
|
||||
router.get('/down', auth, fs, express.json(), async (req, res, next)=>{
|
||||
// check subdomain
|
||||
if(require('../helpers').subdomain(req) !== 'api')
|
||||
next();
|
||||
|
||||
// check if user is verified
|
||||
if((config.strict_email_verification_required || req.user.requires_email_confirmation) && !req.user.email_confirmed)
|
||||
return res.status(400).send({code: 'account_is_not_verified', message: 'Account is not verified'});
|
||||
|
||||
// validation
|
||||
if(!req.query.path)
|
||||
return res.status(400).send('path is required')
|
||||
// path must be a string
|
||||
else if (typeof req.query.path !== 'string')
|
||||
return res.status(400).send('path must be a string.')
|
||||
else if(req.query.path.trim() === '')
|
||||
return res.status(400).send('path cannot be empty')
|
||||
|
||||
// modules
|
||||
const db = req.services.get('database').get(DB_WRITE, 'filesystem');
|
||||
const _path = require('path');
|
||||
const {chkperm} = require('../helpers')
|
||||
const path = _path.resolve('/', req.query.path);
|
||||
const AWS = require('aws-sdk');
|
||||
|
||||
// cannot download the root, because it's a directory!
|
||||
if(path === '/')
|
||||
return res.status(400).send('Cannot download a directory.');
|
||||
|
||||
// resolve path to its FSEntry
|
||||
const fsnode = await req.fs.node(new NodePathSelector(path));
|
||||
|
||||
// not found
|
||||
if( ! fsnode.exists() ) {
|
||||
return res.status(404).send('File not found');
|
||||
}
|
||||
|
||||
// stream data from S3
|
||||
try{
|
||||
const hl_read = new HLRead();
|
||||
const stream = await hl_read.run({
|
||||
fsNode: fsnode,
|
||||
user: req.user,
|
||||
});
|
||||
// let stream = await s3.getObject({
|
||||
// Bucket: fsentry.bucket,
|
||||
// Key: fsentry.uuid, // File name you want to save as in S3
|
||||
// }).createReadStream().on('error', error => {
|
||||
// console.log(error);
|
||||
// });
|
||||
res.attachment(await fsnode.get('name'));
|
||||
return stream.pipe(res);
|
||||
}catch(e){
|
||||
console.log(e);
|
||||
return res.type('application/json').status(500).send({message: 'There was an internal problem reading the file.'});
|
||||
}
|
||||
})
|
||||
|
||||
module.exports = router
|
||||
@@ -19,9 +19,9 @@
|
||||
"use strict"
|
||||
const express = require('express');
|
||||
const router = new express.Router();
|
||||
const config = require('../config');
|
||||
const {validate_signature_auth, get_url_from_req, get_descendants, id2path, get_user, sign_file} = require('../helpers');
|
||||
const { DB_WRITE } = require('../services/database/consts');
|
||||
const { Context } = require('../util/context');
|
||||
|
||||
// -----------------------------------------------------------------------//
|
||||
// GET /file
|
||||
@@ -40,6 +40,10 @@ router.get('/file', async (req, res, next)=>{
|
||||
return res.status(403).send(e);
|
||||
}
|
||||
|
||||
const log = req.services.get('log-service').create('/file');
|
||||
const errors = req.services.get('error-service').create(log);
|
||||
|
||||
|
||||
// modules
|
||||
const db = req.services.get('database').get(DB_WRITE, 'filesystem');
|
||||
const mime = require('mime-types')
|
||||
@@ -113,13 +117,17 @@ router.get('/file', async (req, res, next)=>{
|
||||
|
||||
// stream data from S3
|
||||
try{
|
||||
let stream = await storage.create_read_stream({
|
||||
key: fsentry[0].uuid,
|
||||
let stream = await storage.create_read_stream(fsentry[0].uuid, {
|
||||
bucket: fsentry[0].bucket,
|
||||
bucket_region: fsentry[0].bucket_region,
|
||||
});
|
||||
return stream.pipe(res);
|
||||
}catch(e){
|
||||
errors.report('read from storage', {
|
||||
source: e,
|
||||
trace: true,
|
||||
alarm: true,
|
||||
});
|
||||
return res.type('application/json').status(500).send({message: 'There was an internal problem reading the file.'});
|
||||
}
|
||||
}
|
||||
@@ -167,25 +175,22 @@ router.get('/file', async (req, res, next)=>{
|
||||
// HTTP Status 206 for Partial Content
|
||||
res.writeHead(206, headers);
|
||||
|
||||
// init S3
|
||||
const s3 = new AWS.S3({
|
||||
accessKeyId: config.s3_access_key,
|
||||
secretAccessKey: config.s3_secret_key,
|
||||
region: fsentry[0].bucket_region,
|
||||
});
|
||||
|
||||
try{
|
||||
let stream = await storage.create_read_stream({
|
||||
key: fsentry[0].uuid,
|
||||
const storage = Context.get('storage');
|
||||
let stream = await storage.create_read_stream(fsentry[0].uuid, {
|
||||
bucket: fsentry[0].bucket,
|
||||
bucket_region: fsentry[0].bucket_region,
|
||||
});
|
||||
return stream.pipe(res);
|
||||
}catch(e){
|
||||
console.log(e)
|
||||
errors.report('read from storage', {
|
||||
source: e,
|
||||
trace: true,
|
||||
alarm: true,
|
||||
});
|
||||
return res.type('application/json').status(500).send({message: 'There was an internal problem reading the file.'});
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
module.exports = router
|
||||
module.exports = router
|
||||
@@ -136,9 +136,32 @@ module.exports = eggspress('/batch', {
|
||||
let total_tbd = true;
|
||||
|
||||
const on_first_file = () => {
|
||||
if ( request_error ) {
|
||||
return;
|
||||
}
|
||||
|
||||
// log fileinfos
|
||||
console.log('HERE ARE THE FILEINFOS');
|
||||
console.log(JSON.stringify(fileinfos, null, 2));
|
||||
|
||||
const indexes_to_remove = [];
|
||||
|
||||
for ( let i=0 ; i < pending_operations.length ; i++ ) {
|
||||
const op_spec = pending_operations[i];
|
||||
if ( ! operation_requires_file(op_spec) ) {
|
||||
indexes_to_remove.push(i);
|
||||
console.log(`EXEUCING OP ${op_spec.op}`)
|
||||
response_promises.push(
|
||||
batch_exe.exec_op(req, op_spec)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
for ( let i=indexes_to_remove.length-1 ; i >= 0 ; i-- ) {
|
||||
const index = indexes_to_remove[i];
|
||||
pending_operations.splice(index, 1)[0];
|
||||
response_promises.splice(index, 1);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -150,48 +173,47 @@ module.exports = eggspress('/batch', {
|
||||
});
|
||||
|
||||
const still_reading = new TeePromise();
|
||||
let request_error = null;
|
||||
|
||||
busboy.on('field', (fieldname, value, details) => {
|
||||
if ( details.fieldnameTruncated ) {
|
||||
throw new Error('fieldnameTruncated');
|
||||
}
|
||||
if ( details.valueTruncated ) {
|
||||
throw new Error('valueTruncated');
|
||||
}
|
||||
try {
|
||||
if ( details.fieldnameTruncated ) {
|
||||
throw new Error('fieldnameTruncated');
|
||||
}
|
||||
if ( details.valueTruncated ) {
|
||||
throw new Error('valueTruncated');
|
||||
}
|
||||
|
||||
if ( expected_metadata.hasOwnProperty(fieldname) ) {
|
||||
expected_metadata[fieldname] = value;
|
||||
req.body[fieldname] = value;
|
||||
return;
|
||||
}
|
||||
if ( expected_metadata.hasOwnProperty(fieldname) ) {
|
||||
expected_metadata[fieldname] = value;
|
||||
req.body[fieldname] = value;
|
||||
return;
|
||||
}
|
||||
|
||||
if ( fieldname === 'fileinfo' ) {
|
||||
fileinfos.push(JSON.parse(value));
|
||||
return;
|
||||
}
|
||||
if ( fieldname === 'fileinfo' ) {
|
||||
fileinfos.push(JSON.parse(value));
|
||||
return;
|
||||
}
|
||||
|
||||
if ( ! frame ) {
|
||||
create_frame();
|
||||
}
|
||||
if ( ! frame ) {
|
||||
create_frame();
|
||||
}
|
||||
|
||||
if ( fieldname === 'operation' ) {
|
||||
const op_spec = JSON.parse(value);
|
||||
batch_exe.total++;
|
||||
if ( operation_requires_file(op_spec) ) {
|
||||
console.log(`WAITING FOR FILE ${op_spec.op}`)
|
||||
if ( fieldname === 'operation' ) {
|
||||
const op_spec = JSON.parse(value);
|
||||
batch_exe.total++;
|
||||
pending_operations.push(op_spec);
|
||||
response_promises.push(null);
|
||||
return;
|
||||
}
|
||||
|
||||
console.log(`EXEUCING OP ${op_spec.op}`)
|
||||
response_promises.push(
|
||||
batch_exe.exec_op(req, op_spec)
|
||||
);
|
||||
return;
|
||||
req.body[fieldname] = value;
|
||||
} catch (e) {
|
||||
request_error = e;
|
||||
req.unpipe(busboy);
|
||||
res.set("Connection", "close");
|
||||
res.sendStatus(400);
|
||||
}
|
||||
|
||||
req.body[fieldname] = value;
|
||||
});
|
||||
|
||||
let i = 0;
|
||||
@@ -274,6 +296,11 @@ module.exports = eggspress('/batch', {
|
||||
// Awaiting responses
|
||||
//-------------------------------------------------------------
|
||||
await still_reading;
|
||||
|
||||
if ( request_error ) {
|
||||
return;
|
||||
}
|
||||
|
||||
log.noticeme('WAITING ON OPERATIONS')
|
||||
let responsePromises = response_promises;
|
||||
// let responsePromises = batch_exe.responsePromises;
|
||||
|
||||
@@ -98,6 +98,7 @@ module.exports = eggspress('/readdir', {
|
||||
no_thumbs,
|
||||
no_assocs,
|
||||
user: req.user,
|
||||
actor: req.actor,
|
||||
});
|
||||
|
||||
// check for duplicate names
|
||||
|
||||
@@ -81,10 +81,11 @@ router.get('/get-launch-apps', auth, express.json(), async (req, res, next)=>{
|
||||
'dev-center',
|
||||
'code',
|
||||
'editor',
|
||||
'terminal',
|
||||
'cloudtabs-browserbox',
|
||||
'draw',
|
||||
'camera',
|
||||
'recorder',
|
||||
'terminal',
|
||||
'shell-shockers-outpan',
|
||||
'krunker',
|
||||
'rows',
|
||||
@@ -101,6 +102,7 @@ router.get('/get-launch-apps', auth, express.json(), async (req, res, next)=>{
|
||||
'plushie-connect',
|
||||
'hex-frvr',
|
||||
'spider-solitaire',
|
||||
'test',
|
||||
]
|
||||
|
||||
// Prepare each app for returning to user by only returning the necessary fields
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
/*
|
||||
* Copyright (C) 2024 Puter Technologies Inc.
|
||||
*
|
||||
* This file is part of Puter.
|
||||
*
|
||||
* Puter is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published
|
||||
* by the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
"use strict"
|
||||
const express = require('express');
|
||||
const router = new express.Router();
|
||||
|
||||
// -----------------------------------------------------------------------//
|
||||
// GET /healthcheck
|
||||
// -----------------------------------------------------------------------//
|
||||
router.get('/healthcheck', async (req, res) => {
|
||||
const svc_serverHealth = req.services.get('server-health');
|
||||
|
||||
const status = await svc_serverHealth.get_status();
|
||||
res.json(status);
|
||||
})
|
||||
module.exports = router
|
||||
@@ -56,32 +56,6 @@ router.post('/setItem', auth, express.json(), async (req, res, next)=>{
|
||||
else if(req.body.app && !await app_exists({uid: req.body.app}))
|
||||
return res.status(400).send('`app` does not exist');
|
||||
|
||||
// hash key for faster search in DB
|
||||
const murmurhash = require('murmurhash')
|
||||
const key_hash = murmurhash.v3(req.body.key);
|
||||
|
||||
// database connection
|
||||
const db = require('../../db/mysql.js');
|
||||
|
||||
// insert into DB (in case the row isn't migrated yet)
|
||||
await db.promise().execute(
|
||||
`INSERT INTO kv
|
||||
(user_id, app, kkey_hash, kkey, value)
|
||||
VALUES
|
||||
(?, ?, ?, ?, ?)
|
||||
ON DUPLICATE KEY UPDATE
|
||||
value = ?`,
|
||||
[
|
||||
req.user.id,
|
||||
// 0 is reserved for global system variables
|
||||
req.body.app ?? 'global',
|
||||
key_hash,
|
||||
String(req.body.key),
|
||||
String(req.body.value),
|
||||
String(req.body.value),
|
||||
]
|
||||
)
|
||||
|
||||
// insert into KV 1
|
||||
const actor = req.body.app
|
||||
? await Actor.create(AppUnderUserActorType, {
|
||||
|
||||
@@ -89,7 +89,8 @@ router.post('/login', express.json(), body_parser_error_handler, async (req, res
|
||||
return res.status(400).send('Incorrect password.')
|
||||
// check password
|
||||
if(await bcrypt.compare(req.body.password, user.password)){
|
||||
const token = await jwt.sign({uuid: user.uuid}, config.jwt_secret)
|
||||
const svc_auth = req.services.get('auth');
|
||||
const { token } = await svc_auth.create_session_token(user, { req });
|
||||
//set cookie
|
||||
// res.cookie(config.cookie_name, token);
|
||||
res.cookie(config.cookie_name, token, {
|
||||
|
||||
@@ -31,6 +31,16 @@ router.post('/logout', auth, express.json(), async (req, res, next)=>{
|
||||
next();
|
||||
// delete cookie
|
||||
res.clearCookie(config.cookie_name);
|
||||
// delete session
|
||||
(async () => {
|
||||
if ( ! req.token ) return;
|
||||
try {
|
||||
const svc_auth = req.services.get('auth');
|
||||
await svc_auth.remove_session_by_token(req.token);
|
||||
} catch (e) {
|
||||
console.log(e);
|
||||
}
|
||||
})()
|
||||
//---------------------------------------------------------
|
||||
// DANGER ZONE: delete temp user and all its data
|
||||
//---------------------------------------------------------
|
||||
|
||||
@@ -53,10 +53,15 @@ router.post('/set-pass-using-token', express.json(), async (req, res, next)=>{
|
||||
return res.status(400).send(`Password must be at least ${config.min_pass_length} characters long.`)
|
||||
|
||||
try{
|
||||
await db.write(
|
||||
const info = await db.write(
|
||||
'UPDATE user SET password=?, pass_recovery_token=NULL WHERE `uuid` = ? AND pass_recovery_token = ?',
|
||||
[await bcrypt.hash(req.body.password, 8), req.body.user_id, req.body.token]
|
||||
);
|
||||
|
||||
if ( ! info?.anyRowsAffected ) {
|
||||
return res.status(400).send('Invalid token or user_id.');
|
||||
}
|
||||
|
||||
invalidate_cached_user_by_id(req.body.user_id);
|
||||
|
||||
return res.send('Password successfully updated.')
|
||||
|
||||
@@ -52,6 +52,7 @@ module.exports = eggspress(['/signup'], {
|
||||
const validator = require('validator')
|
||||
let uuid_user;
|
||||
|
||||
const svc_auth = Context.get('services').get('auth');
|
||||
const svc_authAudit = Context.get('services').get('auth-audit');
|
||||
svc_authAudit.record({
|
||||
requester: Context.get('requester'),
|
||||
@@ -67,9 +68,16 @@ module.exports = eggspress(['/signup'], {
|
||||
|
||||
// check if user is already logged in
|
||||
if ( req.body.is_temp && req.cookies[config.cookie_name] ) {
|
||||
const token = req.cookies[config.cookie_name];
|
||||
const decoded = await jwt.verify(token, config.jwt_secret);
|
||||
const user = await get_user({ uuid: decoded.uuid });
|
||||
const { user, token } = await svc_auth.check_session(
|
||||
req.cookies[config.cookie_name]
|
||||
);
|
||||
res.cookie(config.cookie_name, token, {
|
||||
sameSite: 'none',
|
||||
secure: true,
|
||||
httpOnly: true,
|
||||
});
|
||||
// const decoded = await jwt.verify(token, config.jwt_secret);
|
||||
// const user = await get_user({ uuid: decoded.uuid });
|
||||
if ( user ) {
|
||||
return res.send({
|
||||
token: token,
|
||||
@@ -233,17 +241,22 @@ module.exports = eggspress(['/signup'], {
|
||||
db.write('UPDATE `user` SET `last_activity_ts` = now() WHERE id=? LIMIT 1', [pseudo_user.id]);
|
||||
invalidate_cached_user_by_id(pseudo_user.id);
|
||||
}
|
||||
// create token for login
|
||||
const token = await jwt.sign({uuid: user_uuid}, config.jwt_secret);
|
||||
|
||||
// user id
|
||||
// todo if pseudo user, assign directly no need to do another DB lookup
|
||||
const user_id = (pseudo_user === undefined) ? insert_res.insertId : pseudo_user.id;
|
||||
|
||||
const [user] = await db.read(
|
||||
'SELECT * FROM `user` WHERE `id` = ? LIMIT 1',
|
||||
[user_id]
|
||||
);
|
||||
|
||||
// create token for login
|
||||
const { token } = await svc_auth.create_session_token(user, {
|
||||
req,
|
||||
});
|
||||
// jwt.sign({uuid: user_uuid}, config.jwt_secret);
|
||||
|
||||
//-------------------------------------------------------------
|
||||
// email confirmation
|
||||
//-------------------------------------------------------------
|
||||
|
||||
@@ -54,6 +54,7 @@ const WHOAMI_GET = eggspress('/whoami', {
|
||||
is_temp: (req.user.password === null && req.user.email === null),
|
||||
taskbar_items: await get_taskbar_items(req.user),
|
||||
referral_code: req.user.referral_code,
|
||||
...(req.new_token ? { token: req.token } : {})
|
||||
};
|
||||
|
||||
if ( ! is_user ) {
|
||||
@@ -65,6 +66,7 @@ const WHOAMI_GET = eggspress('/whoami', {
|
||||
delete details.desktop_bg_color;
|
||||
delete details.desktop_bg_fit;
|
||||
delete details.taskbar_items;
|
||||
delete details.token;
|
||||
}
|
||||
|
||||
res.send(details);
|
||||
@@ -76,8 +78,19 @@ const WHOAMI_GET = eggspress('/whoami', {
|
||||
const WHOAMI_POST = new express.Router();
|
||||
WHOAMI_POST.post('/whoami', auth, fs, express.json(), async (req, response, next)=>{
|
||||
// check subdomain
|
||||
if(require('../helpers').subdomain(req) !== 'api')
|
||||
next();
|
||||
if(require('../helpers').subdomain(req) !== 'api') {
|
||||
return;
|
||||
}
|
||||
|
||||
const actor = Context.get('actor');
|
||||
if ( ! actor ) {
|
||||
throw Error('actor not found in context');
|
||||
}
|
||||
|
||||
const is_user = actor.type instanceof UserActorType;
|
||||
if ( ! is_user ) {
|
||||
throw Error('actor is not a user');
|
||||
}
|
||||
|
||||
let desktop_items = [];
|
||||
|
||||
|
||||
@@ -507,7 +507,6 @@ module.exports = eggspress('/writeFile', {
|
||||
else{
|
||||
// modules
|
||||
const {uuid2fsentry, id2path} = require('../helpers')
|
||||
const write = require('../filesystem/operations/write.js');
|
||||
const _path = require('path');
|
||||
|
||||
// Check if files were uploaded
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
const { BaseService } = require("../../exports");
|
||||
const { surrounding_box } = require("../fun/dev-console-ui-utils");
|
||||
|
||||
class ComplainAboutVersionsService extends BaseService {
|
||||
static DESCRIPTION = `
|
||||
This service doesn't mandate a specific version of node.js,
|
||||
but it will complain (create a sticky notification in the
|
||||
dev console) if you're using something that's past EOL.
|
||||
|
||||
This is mostly just for fun, because it feels cool when the
|
||||
system calls people out for using old versions of node.
|
||||
That said, maybe one day we'll come across some nuanced error
|
||||
that only happens an a recently EOL'd node version.
|
||||
`;
|
||||
|
||||
static MODULES = {
|
||||
axios: require('axios'),
|
||||
}
|
||||
|
||||
async _init () {
|
||||
const eol_data = await this.get_eol_data_();
|
||||
|
||||
const [major] = process.versions.node.split('.');
|
||||
const current_version_data = eol_data.find(
|
||||
({ cycle }) => cycle === major
|
||||
);
|
||||
|
||||
if ( ! current_version_data ) {
|
||||
this.log.warn(
|
||||
`failed to check ${current_version} in the EOL database`
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const eol_date = new Date(current_version_data.eol);
|
||||
const cur_date_obj = new Date();
|
||||
|
||||
if ( cur_date_obj < eol_date ) {
|
||||
this.log.info('node.js version looks good');
|
||||
return;
|
||||
}
|
||||
|
||||
let timeago = (() => {
|
||||
let years = cur_date_obj.getFullYear() - eol_date.getFullYear();
|
||||
let months = cur_date_obj.getMonth() - eol_date.getMonth();
|
||||
let days = cur_date_obj.getDate() - eol_date.getDate();
|
||||
|
||||
let str = '';
|
||||
while ( years > 0 ) {
|
||||
years -= 1;
|
||||
months += 12;
|
||||
}
|
||||
if ( months > 0 ) {
|
||||
str += `at least ${months} month${months > 1 ? 's' : ''}`;
|
||||
} else {
|
||||
str += `a few days`;
|
||||
}
|
||||
return str;
|
||||
})();
|
||||
|
||||
const widget_lines = [];
|
||||
widget_lines.push(
|
||||
`Node.js version ${major} is past EOL by ${timeago};`,
|
||||
`Everything should work, but you should still upgrade.`,
|
||||
);
|
||||
surrounding_box('31;1', widget_lines);
|
||||
|
||||
const svc_devConsole = this.services.get('dev-console');
|
||||
svc_devConsole.add_widget(() => widget_lines);
|
||||
}
|
||||
|
||||
async get_eol_data_ () {
|
||||
const require = this.require;
|
||||
const axios = require('axios');
|
||||
const url = 'https://endoflife.date/api/nodejs.json'
|
||||
let data;
|
||||
try {
|
||||
({ data } = await axios.get(url));
|
||||
return data;
|
||||
} catch (e) {
|
||||
this.log.error(e);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = ComplainAboutVersionsService;
|
||||
@@ -1,10 +1,11 @@
|
||||
const { surrounding_box } = require("../fun/dev-console-ui-utils");
|
||||
const { get_user, generate_system_fsentries } = require("../helpers");
|
||||
const { get_user, generate_system_fsentries, invalidate_cached_user } = require("../helpers");
|
||||
const { Context } = require("../util/context");
|
||||
const { asyncSafeSetInterval } = require("../util/promise");
|
||||
const BaseService = require("./BaseService");
|
||||
const { Actor, UserActorType } = require("./auth/Actor");
|
||||
const { DB_WRITE } = require("./database/consts");
|
||||
|
||||
const DEFAULT_PASSWORD = 'changeme';
|
||||
const USERNAME = 'default_user';
|
||||
|
||||
class DefaultUserService extends BaseService {
|
||||
@@ -16,13 +17,17 @@ class DefaultUserService extends BaseService {
|
||||
}
|
||||
async ['__on_ready.webserver'] () {
|
||||
// check if a user named `default-user` exists
|
||||
let user = await get_user({ username: USERNAME });
|
||||
let user = await get_user({ username: USERNAME, cached: false });
|
||||
if ( ! user ) user = await this.create_default_user_();
|
||||
|
||||
// check if user named `default-user` is using default password
|
||||
const require = this.require;
|
||||
const tmp_password = await this.get_tmp_password_(user);
|
||||
const bcrypt = require('bcrypt');
|
||||
const is_default_password = await bcrypt.compare(DEFAULT_PASSWORD, user.password);
|
||||
const is_default_password = await bcrypt.compare(
|
||||
tmp_password,
|
||||
user.password
|
||||
);
|
||||
if ( ! is_default_password ) return;
|
||||
|
||||
// show console widget
|
||||
@@ -30,23 +35,26 @@ class DefaultUserService extends BaseService {
|
||||
const lines = [
|
||||
`Your default user has been created!`,
|
||||
`\x1B[31;1musername:\x1B[0m ${USERNAME}`,
|
||||
`\x1B[32;1mpassword:\x1B[0m ${DEFAULT_PASSWORD}`,
|
||||
`\x1B[32;1mpassword:\x1B[0m ${tmp_password}`,
|
||||
`(change the password to remove this message)`
|
||||
];
|
||||
surrounding_box('31;1', lines);
|
||||
return lines;
|
||||
};
|
||||
this.start_poll_();
|
||||
this.start_poll_({ tmp_password, user });
|
||||
const svc_devConsole = this.services.get('dev-console');
|
||||
svc_devConsole.add_widget(this.default_user_widget);
|
||||
}
|
||||
start_poll_ () {
|
||||
start_poll_ ({ tmp_password, user }) {
|
||||
const interval = 1000 * 3; // 3 seconds
|
||||
const poll_interval = asyncSafeSetInterval(async () => {
|
||||
const user = await get_user({ username: USERNAME });
|
||||
const require = this.require;
|
||||
const bcrypt = require('bcrypt');
|
||||
const is_default_password = await bcrypt.compare(DEFAULT_PASSWORD, user.password);
|
||||
const is_default_password = await bcrypt.compare(
|
||||
tmp_password,
|
||||
user.password
|
||||
);
|
||||
if ( ! is_default_password ) {
|
||||
const svc_devConsole = this.services.get('dev-console');
|
||||
svc_devConsole.remove_widget(this.default_user_widget);
|
||||
@@ -56,25 +64,52 @@ class DefaultUserService extends BaseService {
|
||||
}, interval);
|
||||
}
|
||||
async create_default_user_ () {
|
||||
const require = this.require;
|
||||
const bcrypt = require('bcrypt');
|
||||
const db = this.services.get('database').get(DB_WRITE, 'default-user');
|
||||
await db.write(
|
||||
`
|
||||
INSERT INTO user (uuid, username, password, free_storage)
|
||||
VALUES (?, ?, ?, ?)
|
||||
INSERT INTO user (uuid, username, free_storage)
|
||||
VALUES (?, ?, ?)
|
||||
`,
|
||||
[
|
||||
this.modules.uuidv4(),
|
||||
USERNAME,
|
||||
await bcrypt.hash(DEFAULT_PASSWORD, 8),
|
||||
1024 * 1024 * 1024 * 10, // 10 GB
|
||||
],
|
||||
);
|
||||
const user = await get_user({ username: USERNAME });
|
||||
const tmp_password = await this.get_tmp_password_(user);
|
||||
const bcrypt = require('bcrypt');
|
||||
const password_hashed = await bcrypt.hash(tmp_password, 8);
|
||||
await db.write(
|
||||
`UPDATE user SET password = ? WHERE id = ?`,
|
||||
[
|
||||
password_hashed,
|
||||
user.id,
|
||||
],
|
||||
);
|
||||
user.password = password_hashed;
|
||||
await generate_system_fsentries(user);
|
||||
invalidate_cached_user(user);
|
||||
await new Promise(rslv => setTimeout(rslv, 2000));
|
||||
return user;
|
||||
}
|
||||
async get_tmp_password_ (user) {
|
||||
const actor = await Actor.create(UserActorType, { user });
|
||||
return await Context.get().sub({ actor }).arun(async () => {
|
||||
const svc_driver = this.services.get('driver');
|
||||
const driver_response = await svc_driver.call(
|
||||
'puter-kvstore', 'get', { key: 'tmp_password' });
|
||||
|
||||
if ( driver_response.result ) return driver_response.result;
|
||||
|
||||
const tmp_password = require('crypto').randomBytes(4).toString('hex');
|
||||
await svc_driver.call(
|
||||
'puter-kvstore', 'set', {
|
||||
key: 'tmp_password',
|
||||
value: tmp_password });
|
||||
return tmp_password;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = DefaultUserService;
|
||||
@@ -24,6 +24,7 @@ class DevConsoleService extends BaseService {
|
||||
this.static_lines = [];
|
||||
this.widgets = [];
|
||||
this.identifiers = {};
|
||||
this.has_updates = false;
|
||||
}
|
||||
|
||||
turn_on_the_warning_lights () {
|
||||
@@ -39,6 +40,7 @@ class DevConsoleService extends BaseService {
|
||||
if ( opt_id ) {
|
||||
this.identifiers[opt_id] = outputter;
|
||||
}
|
||||
this.mark_updated();
|
||||
}
|
||||
|
||||
remove_widget (id_or_outputter) {
|
||||
@@ -46,9 +48,11 @@ class DevConsoleService extends BaseService {
|
||||
id_or_outputter = this.identifiers[id_or_outputter];
|
||||
}
|
||||
this.widgets = this.widgets.filter(w => w !== id_or_outputter);
|
||||
this.mark_updated();
|
||||
}
|
||||
|
||||
update_ () {
|
||||
const initialOutput = [...this.static_lines];
|
||||
this.static_lines = [];
|
||||
// if a widget throws an error we MUST remove it;
|
||||
// it's probably a stack overflow because it's printing.
|
||||
@@ -64,11 +68,22 @@ class DevConsoleService extends BaseService {
|
||||
output = Array.isArray(output) ? output : [output];
|
||||
this.static_lines.push(...output);
|
||||
}
|
||||
if (!this.arrays_equal(initialOutput, this.static_lines)) {
|
||||
this.mark_updated(); // Update only if outputs have changed
|
||||
}
|
||||
for ( const w of to_remove ) {
|
||||
this.remove_widget(w);
|
||||
}
|
||||
}
|
||||
|
||||
arrays_equal (a, b) {
|
||||
return a.length === b.length && a.every((val, index) => val === b[index]);
|
||||
}
|
||||
|
||||
mark_updated () {
|
||||
this.has_updates = true;
|
||||
}
|
||||
|
||||
async _init () {
|
||||
const services = this.services;
|
||||
// await services.ready;
|
||||
@@ -146,7 +161,10 @@ class DevConsoleService extends BaseService {
|
||||
};
|
||||
|
||||
setInterval(() => {
|
||||
this._redraw();
|
||||
if (this.has_updates) {
|
||||
this._redraw();
|
||||
this.has_updates = false;
|
||||
}
|
||||
}, 2000);
|
||||
|
||||
consoleLogManager.decorate_all(({ replace }, ...args) => {
|
||||
@@ -179,6 +197,11 @@ class DevConsoleService extends BaseService {
|
||||
generateSeparator(text) {
|
||||
text = text || '[ Dev Console ]';
|
||||
const totalWidth = process.stdout.columns;
|
||||
|
||||
if ( totalWidth <= text.length+1 ) {
|
||||
return '═'.repeat(totalWidth < 0 ? 0 : totalWidth);
|
||||
}
|
||||
|
||||
const paddingSize = (totalWidth - text.length) / 2;
|
||||
|
||||
// Construct the separator
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
const BaseService = require("./BaseService");
|
||||
|
||||
class ProxyLogger {
|
||||
constructor (log) {
|
||||
this.log = log;
|
||||
}
|
||||
attach (stream) {
|
||||
let buffer = '';
|
||||
stream.on('data', (chunk) => {
|
||||
buffer += chunk.toString();
|
||||
let lineEndIndex = buffer.indexOf('\n');
|
||||
while (lineEndIndex !== -1) {
|
||||
const line = buffer.substring(0, lineEndIndex);
|
||||
this.log(line);
|
||||
buffer = buffer.substring(lineEndIndex + 1);
|
||||
lineEndIndex = buffer.indexOf('\n');
|
||||
}
|
||||
});
|
||||
|
||||
stream.on('end', () => {
|
||||
if (buffer.length) {
|
||||
this.log(buffer);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @description
|
||||
* This service is used to run webpack watchers.
|
||||
*/
|
||||
class DevWatcherService extends BaseService {
|
||||
static MODULES = {
|
||||
path: require('path'),
|
||||
spawn: require('child_process').spawn,
|
||||
};
|
||||
|
||||
_construct () {
|
||||
this.instances = [];
|
||||
}
|
||||
|
||||
async _init (args) {
|
||||
this.args = args;
|
||||
|
||||
process.on('exit', () => {
|
||||
this.exit_all_();
|
||||
})
|
||||
}
|
||||
|
||||
// Oh geez we need to wait for the web server to initialize
|
||||
// so that `config.origin` has the actual port in it if the
|
||||
// port is set to `auto` - you have no idea how confusing
|
||||
// this was to debug the first time, like Ahhhhhh!!
|
||||
// but hey at least we have this convenient event listener.
|
||||
async ['__on_ready.webserver'] () {
|
||||
const { root, commands } = this.args;
|
||||
for ( const entry of commands ) {
|
||||
const { directory } = entry;
|
||||
const fullpath = this.modules.path.join(
|
||||
root, directory);
|
||||
this.start_({ ...entry, fullpath });
|
||||
}
|
||||
}
|
||||
|
||||
log_ (name, isErr, line) {
|
||||
let txt = `[${name}:`;
|
||||
txt += isErr
|
||||
? `\x1B[31;1merr\x1B[0m`
|
||||
: `\x1B[32;1mout\x1B[0m`;
|
||||
txt += '] ' + line;
|
||||
this.log.info(txt);
|
||||
}
|
||||
|
||||
async start_ ({ name, fullpath, command, args, env }) {
|
||||
this.log.info(`Starting ${name} in ${fullpath}`);
|
||||
const env_processed = { ...(env ?? {}) };
|
||||
for ( const k in env_processed ) {
|
||||
if ( typeof env_processed[k] !== 'function' ) continue;
|
||||
env_processed[k] = env_processed[k]({
|
||||
global_config: this.global_config
|
||||
});
|
||||
}
|
||||
const proc = this.modules.spawn(command, args, {
|
||||
shell: true,
|
||||
env: {
|
||||
...process.env,
|
||||
...env_processed,
|
||||
},
|
||||
cwd: fullpath,
|
||||
});
|
||||
this.instances.push({
|
||||
name, proc,
|
||||
});
|
||||
const out = new ProxyLogger((line) => this.log_(name, false, line));
|
||||
out.attach(proc.stdout);
|
||||
const err = new ProxyLogger((line) => this.log_(name, true, line));
|
||||
err.attach(proc.stderr);
|
||||
proc.on('exit', () => {
|
||||
this.log.info(`[${name}:exit] Process exited (${proc.exitCode})`);
|
||||
this.instances = this.instances.filter((inst) => inst.proc !== proc);
|
||||
})
|
||||
}
|
||||
|
||||
async exit_all_ () {
|
||||
for ( const { proc } of this.instances ) {
|
||||
proc.kill();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = DevWatcherService;
|
||||
@@ -50,6 +50,19 @@ Exciting news! <a href="https://puter.com/app/{{app_name}}">{{app_title}}</a> is
|
||||
|
||||
<p>Best,<br />
|
||||
The Puter Team
|
||||
</p>
|
||||
`,
|
||||
},
|
||||
'email_change_request': {
|
||||
subject: '\u{1f4dd} Confirm your email change',
|
||||
html: `
|
||||
<p>Hi there,</p>
|
||||
<p>
|
||||
We received a request to link this email to the user "{{username}}" on Puter. If you made this request, please click the link below to confirm the change. If you did not make this request, please ignore this email.
|
||||
</p>
|
||||
|
||||
<p>
|
||||
<a href="{{confirm_url}}">Confirm email change</a>
|
||||
</p>
|
||||
`,
|
||||
},
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
const { BaseService } = require("../../exports");
|
||||
const { execSync } = require('child_process');
|
||||
const config = require("../config");
|
||||
|
||||
class HostDiskUsageService extends BaseService {
|
||||
static DESCRIPTION = `
|
||||
This service is responsible for identifying the mountpoint/drive
|
||||
on which the current process working directory is running, and then checking the
|
||||
disk usage of that mountpoint/drive.
|
||||
`;
|
||||
|
||||
async _init() {
|
||||
const current_platform = process.platform;
|
||||
|
||||
// Setting the available space to a large number for unhandled platforms
|
||||
var free_space = 1e+14;
|
||||
|
||||
if (current_platform == "darwin") {
|
||||
const mountpoint = this.get_darwin_mountpoint(process.cwd());
|
||||
free_space = this.get_disk_capacity_darwin(mountpoint);
|
||||
} else if (current_platform == "linux") {
|
||||
const mountpoint = this.get_linux_mountpint(process.cwd());
|
||||
free_space = this.get_disk_capacity_linux(mountpoint);
|
||||
} else if (current_platform == "win32") {
|
||||
this.log.warn('HostDiskUsageService: Windows is not supported yet');
|
||||
// TODO: Implement for windows systems
|
||||
}
|
||||
|
||||
console.log('free_space:', free_space);
|
||||
config.available_device_storage = free_space;
|
||||
}
|
||||
|
||||
// TODO: TTL cache this value
|
||||
get_host_usage () {
|
||||
const current_platform = process.platform;
|
||||
|
||||
let disk_use = 0;
|
||||
if (current_platform == "darwin") {
|
||||
const mountpoint = this.get_darwin_mountpoint(process.cwd());
|
||||
disk_use = this.get_disk_use_darwin(mountpoint);
|
||||
} else if (current_platform == "linux") {
|
||||
const mountpoint = this.get_linux_mountpint(process.cwd());
|
||||
disk_use = this.get_disk_use_linux(mountpoint);
|
||||
} else if (current_platform == "win32") {
|
||||
this.log.warn('HostDiskUsageService: Windows is not supported yet');
|
||||
// TODO: Implement for windows systems
|
||||
}
|
||||
return disk_use;
|
||||
}
|
||||
|
||||
// Called by the /df endpoint
|
||||
get_extra () {
|
||||
return {
|
||||
host_used: this.get_host_usage(),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
// Get the mountpoint/drive of the current working directory in mac os
|
||||
get_darwin_mountpoint(directory) {
|
||||
return execSync(`df -P "${directory}" | awk 'NR==2 {print $6}'`, { encoding: 'utf-8' }).trim();
|
||||
}
|
||||
|
||||
// Get the mountpoint/drive of the current working directory in linux
|
||||
get_linux_mountpint(directory) {
|
||||
return execSync(`df -P "${directory}" | awk 'NR==2 {print $6}'`, { encoding: 'utf-8' }).trim();
|
||||
// TODO: Implement for linux systems
|
||||
}
|
||||
|
||||
// Get the drive of the current working directory in windows
|
||||
get_windows_drive(directory) {
|
||||
// TODO: Implement for windows systems
|
||||
}
|
||||
|
||||
// Get the free space on the mountpoint/drive in mac os
|
||||
get_disk_capacity_darwin(mountpoint) {
|
||||
const disk_info = execSync(`df -P "${mountpoint}" | awk 'NR==2 {print $2}'`, { encoding: 'utf-8' }).trim().split(' ');
|
||||
return parseInt(disk_info) * 512;
|
||||
}
|
||||
|
||||
// Get the free space on the mountpoint/drive in linux
|
||||
get_disk_capacity_linux(mountpoint) {
|
||||
const disk_info = execSync(`df -P "${mountpoint}" | awk 'NR==2 {print $2}'`, { encoding: 'utf-8' }).trim().split(' ');
|
||||
return parseInt(disk_info) * 1024;
|
||||
}
|
||||
|
||||
// Get the free space on the drive in windows
|
||||
get_disk_capacity_windows(drive) {
|
||||
// TODO: Implement for windows systems
|
||||
}
|
||||
|
||||
// Get the free space on the mountpoint/drive in mac os
|
||||
get_disk_use_darwin(mountpoint) {
|
||||
const disk_info = execSync(`df -P "${mountpoint}" | awk 'NR==2 {print $4}'`, { encoding: 'utf-8' }).trim().split(' ');
|
||||
return parseInt(disk_info) * 512;
|
||||
}
|
||||
|
||||
// Get the free space on the mountpoint/drive in linux
|
||||
get_disk_use_linux(mountpoint) {
|
||||
const disk_info = execSync(`df -P "${mountpoint}" | awk 'NR==2 {print $4}'`, { encoding: 'utf-8' }).trim().split(' ');
|
||||
return parseInt(disk_info) * 1024;
|
||||
}
|
||||
|
||||
// Get the free space on the drive in windows
|
||||
get_disk_use_windows(drive) {
|
||||
// TODO: Implement for windows systems
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = HostDiskUsageService;
|
||||
@@ -22,7 +22,6 @@ class PuterAPIService extends BaseService {
|
||||
async ['__on_install.routes'] () {
|
||||
const { app } = this.services.get('web-server');
|
||||
|
||||
app.use(require('../routers/version'))
|
||||
app.use(require('../routers/apps'))
|
||||
app.use(require('../routers/query/app'))
|
||||
app.use(require('../routers/change_username'))
|
||||
@@ -30,14 +29,20 @@ class PuterAPIService extends BaseService {
|
||||
app.use(require('../routers/auth/get-user-app-token'))
|
||||
app.use(require('../routers/auth/grant-user-app'))
|
||||
app.use(require('../routers/auth/revoke-user-app'))
|
||||
app.use(require('../routers/auth/grant-user-user'));
|
||||
app.use(require('../routers/auth/revoke-user-user'));
|
||||
app.use(require('../routers/auth/list-permissions'))
|
||||
app.use(require('../routers/auth/list-sessions'))
|
||||
app.use(require('../routers/auth/revoke-session'))
|
||||
app.use(require('../routers/auth/check-app'))
|
||||
app.use(require('../routers/auth/app-uid-from-origin'))
|
||||
app.use(require('../routers/auth/create-access-token'))
|
||||
app.use(require('../routers/auth/delete-own-user'))
|
||||
app.use(require('../routers/drivers/call'))
|
||||
app.use(require('../routers/drivers/list-interfaces'))
|
||||
app.use(require('../routers/drivers/usage'))
|
||||
app.use(require('../routers/confirm-email'))
|
||||
app.use(require('../routers/down'))
|
||||
app.use(require('../routers/contactUs'))
|
||||
app.use(require('../routers/delete-site'))
|
||||
app.use(require('../routers/get-dev-profile'))
|
||||
@@ -66,6 +71,7 @@ class PuterAPIService extends BaseService {
|
||||
app.use(require('../routers/sites'))
|
||||
// app.use(require('../routers/filesystem_api/stat'))
|
||||
app.use(require('../routers/suggest_apps'))
|
||||
app.use(require('../routers/healthcheck'))
|
||||
app.use(require('../routers/test'))
|
||||
app.use(require('../routers/update-taskbar-items'))
|
||||
require('../routers/whoami')(app);
|
||||
|
||||
@@ -33,7 +33,7 @@ class PuterSiteService extends BaseService {
|
||||
root_dir_id: this.config.devtest_directory,
|
||||
};
|
||||
}
|
||||
const rows = await this.read(
|
||||
const rows = await this.db.read(
|
||||
`SELECT * FROM subdomains WHERE subdomain = ? LIMIT 1`,
|
||||
[subdomain]
|
||||
);
|
||||
|
||||
@@ -16,74 +16,26 @@
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
const { AdvancedBase } = require("puter-js-common");
|
||||
const { NodeUIDSelector } = require("../filesystem/node/selectors");
|
||||
const { get_user } = require("../helpers");
|
||||
const { TeePromise } = require("../util/promise");
|
||||
const { StreamBuffer } = require("../util/streamutil");
|
||||
const BaseService = require("./BaseService");
|
||||
|
||||
class PuterVersionService extends AdvancedBase {
|
||||
static MODULES = {
|
||||
_path: require('path'),
|
||||
fs: require('fs'),
|
||||
_exec: require('child_process').execSync,
|
||||
axios: require('axios'),
|
||||
class PuterVersionService extends BaseService {
|
||||
async _init () {
|
||||
this.boot_time = Date.now();
|
||||
}
|
||||
|
||||
constructor ({ services, config }) {
|
||||
super();
|
||||
this.fs = services.get('filesystem');
|
||||
this.config = config;
|
||||
|
||||
this._init({ config });
|
||||
this.ready_ = new TeePromise();
|
||||
}
|
||||
|
||||
async _init ({ config }) {
|
||||
// this.node = await this.fs.node(new NodeUIDSelector(config.puter_hosted_data.puter_versions));
|
||||
// this.user = await get_user({ username: 'puter' });
|
||||
|
||||
// await this._poll_versions({ config });
|
||||
|
||||
// setInterval(async () => {
|
||||
// await this._poll_versions({ config });
|
||||
// }, 60 * 1000);
|
||||
}
|
||||
|
||||
// not used anymore - this was for getting version numbers from a file hosted on puter
|
||||
async _poll_versions ({ config }) {
|
||||
const resp = await this.modules.axios.get(
|
||||
config.puter_hosted_data.puter_versions
|
||||
);
|
||||
this.versions_ = resp.data.versions;
|
||||
this.ready_.resolve();
|
||||
async ['__on_install.routes'] () {
|
||||
const { app } = this.services.get('web-server');
|
||||
app.use(require('../routers/version'));
|
||||
}
|
||||
|
||||
get_version () {
|
||||
let git_version;
|
||||
let deploy_timestamp;
|
||||
if ( this.config.env === 'dev' ) {
|
||||
// get commit hash from git
|
||||
git_version = this.modules._exec('git describe --tags', {
|
||||
cwd: this.modules._path.join(__dirname, '../../'),
|
||||
encoding: 'utf8',
|
||||
}).trim();
|
||||
deploy_timestamp = Date.now();
|
||||
} else {
|
||||
// get git version from file
|
||||
const path = this.modules._path.join(__dirname, '../../git_version');
|
||||
|
||||
git_version = this.modules.fs.readFileSync(path, 'utf8').trim();
|
||||
deploy_timestamp = Number.parseInt((this.modules.fs.readFileSync(
|
||||
this.modules._path.join(__dirname, '../../deploy_timestamp'),
|
||||
'utf8'
|
||||
)).trim());
|
||||
}
|
||||
const version = process.env.npm_package_version ||
|
||||
require('../../package.json').version;
|
||||
return {
|
||||
version: git_version,
|
||||
environment: this.config.env,
|
||||
location: this.config.server_id,
|
||||
deploy_timestamp,
|
||||
version,
|
||||
environment: this.global_config.env,
|
||||
location: this.global_config.server_id,
|
||||
deploy_timestamp: this.boot_time,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
const BaseService = require("./BaseService");
|
||||
|
||||
class ServeStaticFilesService extends BaseService {
|
||||
async _init (args) {
|
||||
this.directories = args.directories;
|
||||
}
|
||||
|
||||
async ['__on_install.routes'] () {
|
||||
const { app } = this.services.get('web-server');
|
||||
|
||||
for ( const { prefix, path } of this.directories ) {
|
||||
app.use(prefix, require('express').static(path));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = ServeStaticFilesService;
|
||||
@@ -25,14 +25,14 @@ class ServeGUIService extends BaseService {
|
||||
async ['__on_install.routes-gui'] () {
|
||||
const { app } = this.services.get('web-server');
|
||||
|
||||
// is this a puter.site domain?
|
||||
require('../routers/hosting/puter-site')(app);
|
||||
|
||||
// Router for all other cases
|
||||
app.use(require('../routers/_default'))
|
||||
|
||||
// Static files
|
||||
app.use(express.static(_path.join(__dirname, '../../public')))
|
||||
|
||||
// is this a puter.site domain?
|
||||
require('../routers/hosting/puter-site')(app);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
const { invalidate_cached_user, get_user } = require("../helpers");
|
||||
const { asyncSafeSetInterval } = require("../util/promise");
|
||||
const { MINUTE, SECOND } = require("../util/time");
|
||||
const BaseService = require("./BaseService");
|
||||
const { DB_WRITE } = require("./database/consts");
|
||||
|
||||
/**
|
||||
* This service is responsible for updating session activity
|
||||
* timestamps and maintaining the number of active sessions.
|
||||
*/
|
||||
class SessionService extends BaseService {
|
||||
static MODULES = {
|
||||
// uuidv5: require('uuid').v5,
|
||||
uuidv4: require('uuid').v4,
|
||||
}
|
||||
|
||||
_construct () {
|
||||
this.sessions = {};
|
||||
}
|
||||
|
||||
async _init () {
|
||||
this.db = await this.services.get('database').get(DB_WRITE, 'session');
|
||||
|
||||
(async () => {
|
||||
// TODO: change to 5 minutes or configured value
|
||||
asyncSafeSetInterval(async () => {
|
||||
await this._update_sessions();
|
||||
}, 2 * MINUTE);
|
||||
})();
|
||||
}
|
||||
|
||||
async create_session (user, meta) {
|
||||
const unix_ts = Math.floor(Date.now() / 1000);
|
||||
|
||||
meta = {
|
||||
// clone
|
||||
...(meta || {}),
|
||||
};
|
||||
meta.created = new Date().toISOString();
|
||||
meta.created_unix = unix_ts;
|
||||
const uuid = this.modules.uuidv4();
|
||||
await this.db.write(
|
||||
'INSERT INTO `sessions` ' +
|
||||
'(`uuid`, `user_id`, `meta`, `last_activity`, `created_at`) ' +
|
||||
'VALUES (?, ?, ?, ?, ?)',
|
||||
[uuid, user.id, JSON.stringify(meta), unix_ts, unix_ts],
|
||||
);
|
||||
const session = {
|
||||
last_touch: Date.now(),
|
||||
last_store: Date.now(),
|
||||
uuid,
|
||||
user_uid: user.uuid,
|
||||
user_id: user.id,
|
||||
meta,
|
||||
};
|
||||
this.sessions[uuid] = session;
|
||||
|
||||
return session;
|
||||
}
|
||||
|
||||
async get_session_ (uuid) {
|
||||
let session = this.sessions[uuid];
|
||||
if ( session ) {
|
||||
session.last_touch = Date.now();
|
||||
return session;
|
||||
}
|
||||
;[session] = await this.db.read(
|
||||
"SELECT * FROM `sessions` WHERE `uuid` = ? LIMIT 1",
|
||||
[uuid],
|
||||
);
|
||||
if ( ! session ) return;
|
||||
session.last_store = Date.now();
|
||||
session.meta = this.db.case({
|
||||
mysql: () => session.meta,
|
||||
otherwise: () => JSON.parse(session.meta ?? "{}")
|
||||
})();
|
||||
const user = await get_user(session.user_id);
|
||||
session.user_uid = user?.uuid;
|
||||
this.sessions[uuid] = session;
|
||||
return session;
|
||||
}
|
||||
async get_session (uuid) {
|
||||
const session = await this.get_session_(uuid);
|
||||
if ( session ) {
|
||||
session.last_touch = Date.now();
|
||||
session.meta.last_activity = (new Date()).toISOString();
|
||||
}
|
||||
return this.remove_internal_values_(session);
|
||||
}
|
||||
|
||||
remove_internal_values_ (session) {
|
||||
const copy = {
|
||||
...session,
|
||||
};
|
||||
delete copy.last_touch;
|
||||
delete copy.last_store;
|
||||
delete copy.user_id;
|
||||
return copy;
|
||||
}
|
||||
|
||||
get_user_sessions (user) {
|
||||
const sessions = [];
|
||||
for ( const session of Object.values(this.sessions) ) {
|
||||
if ( session.user_id === user.id ) {
|
||||
sessions.push(session);
|
||||
}
|
||||
}
|
||||
return sessions.map(this.remove_internal_values_.bind(this));
|
||||
}
|
||||
|
||||
remove_session (uuid) {
|
||||
delete this.sessions[uuid];
|
||||
return this.db.write(
|
||||
'DELETE FROM `sessions` WHERE `uuid` = ?',
|
||||
[uuid],
|
||||
);
|
||||
}
|
||||
|
||||
async _update_sessions () {
|
||||
this.log.tick('UPDATING SESSIONS');
|
||||
const now = Date.now();
|
||||
const keys = Object.keys(this.sessions);
|
||||
|
||||
const user_updates = {};
|
||||
|
||||
for ( const key of keys ) {
|
||||
const session = this.sessions[key];
|
||||
if ( now - session.last_store > 5 * MINUTE ) {
|
||||
this.log.debug('storing session meta: ' + session.uuid);
|
||||
const unix_ts = Math.floor(now / 1000);
|
||||
await this.db.write(
|
||||
'UPDATE `sessions` ' +
|
||||
'SET `meta` = ?, `last_activity` = ? ' +
|
||||
'WHERE `uuid` = ?',
|
||||
[JSON.stringify(session.meta), unix_ts, session.uuid],
|
||||
);
|
||||
session.last_store = now;
|
||||
if (
|
||||
! user_updates[session.user_id] ||
|
||||
user_updates[session.user_id][1] < session.last_touch
|
||||
) {
|
||||
user_updates[session.user_id] = [session.user_id, session.last_touch];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for ( const [user_id, last_touch] of Object.values(user_updates) ) {
|
||||
const sql_ts = (date =>
|
||||
date.toISOString().split('T')[0] + ' '
|
||||
+ date.toTimeString().split(' ')[0]
|
||||
)(new Date(last_touch));
|
||||
|
||||
await this.db.write(
|
||||
'UPDATE `user` ' +
|
||||
'SET `last_activity_ts` = ? ' +
|
||||
'WHERE `id` = ? LIMIT 1',
|
||||
[sql_ts, user_id],
|
||||
);
|
||||
const user = kv.get('users:id:' + user_id);
|
||||
if ( user ) {
|
||||
user.last_activity_ts = sql_ts;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { SessionService };
|
||||
@@ -128,8 +128,8 @@ class WebServerService extends BaseService {
|
||||
return lines;
|
||||
};
|
||||
{
|
||||
const svc_devConsole = this.services.get('dev-console');
|
||||
svc_devConsole.add_widget(this.startup_widget);
|
||||
const svc_devConsole = this.services.get('dev-console', { optional: true });
|
||||
if ( svc_devConsole ) svc_devConsole.add_widget(this.startup_widget);
|
||||
}
|
||||
|
||||
this.print_puter_logo_();
|
||||
@@ -208,6 +208,24 @@ class WebServerService extends BaseService {
|
||||
responseTime: parseFloat(responseTime),
|
||||
};
|
||||
if ( url.includes('android-icon') ) return;
|
||||
|
||||
// remove `puter.auth.*` query params
|
||||
const safe_url = (u => {
|
||||
// We need to prepend an arbitrary domain to the URL
|
||||
const url = new URL('https://example.com' + u);
|
||||
const search = url.searchParams;
|
||||
for ( const key of search.keys() ) {
|
||||
if ( key.startsWith('puter.auth.') ) search.delete(key);
|
||||
}
|
||||
return url.pathname + '?' + search.toString();
|
||||
})(fields.url);
|
||||
fields.url = safe_url;
|
||||
// re-write message
|
||||
message = [
|
||||
fields.method, fields.url,
|
||||
fields.status, fields.responseTime,
|
||||
].join(' ');
|
||||
|
||||
const log = this.services.get('log-service').create('morgan');
|
||||
log.info(message, fields);
|
||||
}
|
||||
@@ -291,7 +309,10 @@ class WebServerService extends BaseService {
|
||||
res.setHeader('Access-Control-Allow-Origin', origin ?? '*');
|
||||
}
|
||||
// Website(s) to allow to connect
|
||||
if ( req.subdomains[0] === 'api' ) {
|
||||
if (
|
||||
config.experimental_no_subdomain ||
|
||||
req.subdomains[req.subdomains.length-1] === 'api'
|
||||
) {
|
||||
res.setHeader('Access-Control-Allow-Origin', origin ?? '*');
|
||||
res.setHeader('Access-Control-Allow-Credentials', 'true');
|
||||
}
|
||||
@@ -315,6 +336,13 @@ class WebServerService extends BaseService {
|
||||
// res.setHeader('Cross-Origin-Embedder-Policy', 'require-corp')
|
||||
res.setHeader('Cross-Origin-Resource-Policy', 'cross-origin');
|
||||
// Pass to next layer of middleware
|
||||
|
||||
// disable iframes on the main domain
|
||||
if ( req.hostname === config.domain ) {
|
||||
// disable iframes
|
||||
res.setHeader('X-Frame-Options', 'SAMEORIGIN');
|
||||
}
|
||||
|
||||
next();
|
||||
});
|
||||
|
||||
@@ -329,9 +357,13 @@ class WebServerService extends BaseService {
|
||||
{
|
||||
id: 'dismiss',
|
||||
description: 'Dismiss the startup message',
|
||||
handler: async () => {
|
||||
const svc_devConsole = this.services.get('dev-console');
|
||||
svc_devConsole.remove_widget(this.startup_widget);
|
||||
handler: async (_, log) => {
|
||||
if ( ! this.startup_widget ) return;
|
||||
const svc_devConsole = this.services.get('dev-console', { optional: true });
|
||||
if ( svc_devConsole ) svc_devConsole.remove_widget(this.startup_widget);
|
||||
const lines = this.startup_widget();
|
||||
for ( const line of lines ) log.log(line);
|
||||
this.startup_widget = null;
|
||||
}
|
||||
}
|
||||
]);
|
||||
|
||||
@@ -25,13 +25,16 @@ const { AppUnderUserActorType, UserActorType, Actor, SystemActorType, AccessToke
|
||||
|
||||
class ACLService extends BaseService {
|
||||
async check (actor, resource, mode) {
|
||||
const result = await this._check_fsNode(actor, resource, mode);
|
||||
if ( this.verbose ) console.log('LOGGING ACL CHECK', {
|
||||
actor, mode,
|
||||
// trace: (new Error()).stack,
|
||||
result,
|
||||
const ld = (Context.get('logdent') ?? 0) + 1;
|
||||
return await Context.get().sub({ logdent: ld }).arun(async () => {
|
||||
const result = await this._check_fsNode(actor, resource, mode);
|
||||
if ( this.verbose ) console.log('LOGGING ACL CHECK', {
|
||||
actor, mode,
|
||||
// trace: (new Error()).stack,
|
||||
result,
|
||||
});
|
||||
return result;
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
||||
async _check_fsNode (actor, fsNode, mode) {
|
||||
@@ -76,35 +79,6 @@ class ACLService extends BaseService {
|
||||
}
|
||||
}
|
||||
|
||||
// Hard rule: if actor is owner, allow
|
||||
if ( actor.type instanceof UserActorType ) {
|
||||
const owner = await fsNode.get('user_id');
|
||||
if ( this.verbose ) {
|
||||
const user = await get_user({ id: owner });
|
||||
this.log.info(
|
||||
`user ${user.username} is ` +
|
||||
(owner == actor.type.user.id ? '' : 'not ') +
|
||||
'owner of ' + await fsNode.get('path'), {
|
||||
actor_user_id: actor.type.user.id,
|
||||
fsnode_user_id: owner,
|
||||
}
|
||||
);
|
||||
}
|
||||
if ( owner == actor.type.user.id ) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// For these actors, deny if the user component is not the owner
|
||||
// -> user
|
||||
// -> app-under-user
|
||||
if ( ! (actor.type instanceof AccessTokenActorType) ) {
|
||||
const owner = await fsNode.get('user_id');
|
||||
if ( owner != actor.type.user.id ) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// app-under-user only works if the user also has permission
|
||||
if ( actor.type instanceof AppUnderUserActorType ) {
|
||||
const user_actor = new Actor({
|
||||
@@ -146,6 +120,7 @@ class ACLService extends BaseService {
|
||||
return APIError.create('forbidden');
|
||||
}
|
||||
|
||||
// TODO: DRY: Also in FilesystemService
|
||||
_higher_modes (mode) {
|
||||
// If you want to X, you can do so with any of [...Y]
|
||||
if ( mode === 'see' ) return ['see', 'list', 'read', 'write'];
|
||||
|
||||
@@ -25,6 +25,8 @@ const { DB_WRITE } = require("../database/consts");
|
||||
|
||||
const APP_ORIGIN_UUID_NAMESPACE = '33de3768-8ee0-43e9-9e73-db192b97a5d8';
|
||||
|
||||
const LegacyTokenError = class extends Error {};
|
||||
|
||||
class AuthService extends BaseService {
|
||||
static MODULES = {
|
||||
jwt: require('jsonwebtoken'),
|
||||
@@ -34,6 +36,9 @@ class AuthService extends BaseService {
|
||||
|
||||
async _init () {
|
||||
this.db = await this.services.get('database').get(DB_WRITE, 'auth');
|
||||
this.svc_session = await this.services.get('session');
|
||||
|
||||
this.sessions = {};
|
||||
}
|
||||
|
||||
async authenticate_from_token (token) {
|
||||
@@ -43,6 +48,7 @@ class AuthService extends BaseService {
|
||||
);
|
||||
|
||||
if ( ! decoded.hasOwnProperty('type') ) {
|
||||
throw new LegacyTokenError();
|
||||
const user = await this.db.requireRead(
|
||||
"SELECT * FROM `user` WHERE `uuid` = ? LIMIT 1",
|
||||
[decoded.uuid],
|
||||
@@ -66,6 +72,26 @@ class AuthService extends BaseService {
|
||||
});
|
||||
}
|
||||
|
||||
if ( decoded.type === 'session' ) {
|
||||
const session = await this.get_session_(decoded.uuid);
|
||||
|
||||
if ( ! session ) {
|
||||
throw APIError.create('token_auth_failed');
|
||||
}
|
||||
|
||||
const user = await get_user({ uuid: decoded.user_uid });
|
||||
|
||||
const actor_type = new UserActorType({
|
||||
user,
|
||||
session: session.uuid,
|
||||
});
|
||||
|
||||
return new Actor({
|
||||
user_uid: decoded.user_uid,
|
||||
type: actor_type,
|
||||
});
|
||||
}
|
||||
|
||||
if ( decoded.type === 'app-under-user' ) {
|
||||
const user = await get_user({ uuid: decoded.user_uid });
|
||||
if ( ! user ) {
|
||||
@@ -149,6 +175,129 @@ class AuthService extends BaseService {
|
||||
return token;
|
||||
}
|
||||
|
||||
async create_session_ (user, meta = {}) {
|
||||
this.log.info(`CREATING SESSION`);
|
||||
|
||||
if ( meta.req ) {
|
||||
const req = meta.req;
|
||||
delete meta.req;
|
||||
|
||||
const ip = this.global_config.fowarded
|
||||
? req.headers['x-forwarded-for'] ||
|
||||
req.connection.remoteAddress
|
||||
: req.connection.remoteAddress
|
||||
;
|
||||
|
||||
meta.ip = ip;
|
||||
|
||||
meta.server = this.global_config.server_id;
|
||||
|
||||
if ( req.headers['user-agent'] ) {
|
||||
meta.user_agent = req.headers['user-agent'];
|
||||
}
|
||||
|
||||
if ( req.headers['referer'] ) {
|
||||
meta.referer = req.headers['referer'];
|
||||
}
|
||||
|
||||
if ( req.headers['origin'] ) {
|
||||
const origin = this._origin_from_url(req.headers['origin']);
|
||||
if ( origin ) {
|
||||
meta.origin = origin;
|
||||
}
|
||||
}
|
||||
|
||||
if ( req.headers['host'] ) {
|
||||
const host = this._origin_from_url(req.headers['host']);
|
||||
if ( host ) {
|
||||
meta.host = host;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return await this.svc_session.create_session(user, meta);
|
||||
}
|
||||
|
||||
async get_session_ (uuid) {
|
||||
return await this.svc_session.get_session(uuid);
|
||||
}
|
||||
|
||||
async create_session_token (user, meta) {
|
||||
const session = await this.create_session_(user, meta);
|
||||
|
||||
const token = this.modules.jwt.sign({
|
||||
type: 'session',
|
||||
version: '0.0.0',
|
||||
uuid: session.uuid,
|
||||
meta: session.meta,
|
||||
user_uid: user.uuid,
|
||||
}, this.global_config.jwt_secret);
|
||||
|
||||
return { session, token };
|
||||
}
|
||||
|
||||
async check_session (cur_token, meta) {
|
||||
const decoded = this.modules.jwt.verify(
|
||||
cur_token, this.global_config.jwt_secret
|
||||
);
|
||||
|
||||
console.log('\x1B[36;1mDECODED SESSION', decoded);
|
||||
|
||||
if ( decoded.type && decoded.type !== 'session' ) {
|
||||
return {};
|
||||
}
|
||||
|
||||
const is_legacy = ! decoded.type;
|
||||
|
||||
const user = await get_user({ uuid:
|
||||
is_legacy ? decoded.uuid : decoded.user_uid
|
||||
});
|
||||
if ( ! user ) {
|
||||
return {};
|
||||
}
|
||||
|
||||
if ( ! is_legacy ) {
|
||||
// Ensure session exists
|
||||
const session = await this.get_session_(decoded.uuid);
|
||||
if ( ! session ) {
|
||||
return {};
|
||||
}
|
||||
|
||||
// Return the session
|
||||
return { user, token: cur_token };
|
||||
}
|
||||
|
||||
this.log.info(`UPGRADING SESSION`);
|
||||
|
||||
// Upgrade legacy token
|
||||
// TODO: phase this out
|
||||
const { session, token } = await this.create_session_token(user, meta);
|
||||
|
||||
const actor_type = new UserActorType({
|
||||
user,
|
||||
session,
|
||||
});
|
||||
|
||||
const actor = new Actor({
|
||||
user_uid: user.uuid,
|
||||
type: actor_type,
|
||||
});
|
||||
|
||||
return { actor, user, token };
|
||||
}
|
||||
|
||||
async remove_session_by_token (token) {
|
||||
const decoded = this.modules.jwt.verify(
|
||||
token, this.global_config.jwt_secret
|
||||
);
|
||||
|
||||
if ( decoded.type !== 'session' ) {
|
||||
return;
|
||||
}
|
||||
|
||||
await this.svc_session.remove_session(decoded.uuid);
|
||||
}
|
||||
|
||||
async create_access_token (authorizer, permissions) {
|
||||
const jwt_obj = {};
|
||||
const authorizer_obj = {};
|
||||
@@ -206,6 +355,48 @@ class AuthService extends BaseService {
|
||||
return jwt;
|
||||
}
|
||||
|
||||
async list_sessions (actor) {
|
||||
const seen = new Set();
|
||||
const sessions = [];
|
||||
|
||||
const cache_sessions = this.svc_session.get_user_sessions(actor.type.user);
|
||||
for ( const session of cache_sessions ) {
|
||||
seen.add(session.uuid);
|
||||
sessions.push(session);
|
||||
}
|
||||
|
||||
// We won't take the cached sessions here because it's
|
||||
// possible the user has sessions on other servers
|
||||
const db_sessions = await this.db.read(
|
||||
'SELECT uuid, meta FROM `sessions` WHERE `user_id` = ?',
|
||||
[actor.type.user.id],
|
||||
);
|
||||
|
||||
for ( const session of db_sessions ) {
|
||||
if ( seen.has(session.uuid) ) {
|
||||
continue;
|
||||
}
|
||||
session.meta = this.db.case({
|
||||
mysql: () => session.meta,
|
||||
otherwise: () => JSON.parse(session.meta ?? "{}")
|
||||
})();
|
||||
if ( session.uuid === actor.type.session ) {
|
||||
session.current = true;
|
||||
}
|
||||
sessions.push(session);
|
||||
};
|
||||
|
||||
return sessions;
|
||||
}
|
||||
|
||||
async revoke_session (actor, uuid) {
|
||||
delete this.sessions[uuid];
|
||||
await this.db.write(
|
||||
`DELETE FROM sessions WHERE uuid = ? AND user_id = ?`,
|
||||
[uuid, actor.type.user.id]
|
||||
);
|
||||
}
|
||||
|
||||
async get_user_app_token_from_origin (origin) {
|
||||
origin = this._origin_from_url(origin);
|
||||
const app_uid = await this._app_uid_from_origin(origin);
|
||||
@@ -264,4 +455,5 @@ class AuthService extends BaseService {
|
||||
|
||||
module.exports = {
|
||||
AuthService,
|
||||
LegacyTokenError,
|
||||
};
|
||||
@@ -17,6 +17,7 @@
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
const { get_user, get_app } = require("../../helpers");
|
||||
const { Context } = require("../../util/context");
|
||||
const BaseService = require("../BaseService");
|
||||
const { DB_WRITE } = require("../database/consts");
|
||||
const { UserActorType, Actor, AppUnderUserActorType, AccessTokenActorType } = require("./Actor");
|
||||
@@ -84,6 +85,10 @@ const implicit_user_app_permissions = [
|
||||
},
|
||||
];
|
||||
|
||||
const implicit_user_permissions = {
|
||||
'driver': {},
|
||||
};
|
||||
|
||||
class PermissionRewriter {
|
||||
static create ({ id, matcher, rewriter }) {
|
||||
return new PermissionRewriter({ id, matcher, rewriter });
|
||||
@@ -104,6 +109,32 @@ class PermissionRewriter {
|
||||
}
|
||||
}
|
||||
|
||||
class PermissionImplicator {
|
||||
static create ({ id, matcher, checker }) {
|
||||
return new PermissionImplicator({ id, matcher, checker });
|
||||
}
|
||||
|
||||
constructor ({ id, matcher, checker }) {
|
||||
this.id = id;
|
||||
this.matcher = matcher;
|
||||
this.checker = checker;
|
||||
}
|
||||
|
||||
matches (permission) {
|
||||
return this.matcher(permission);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the permission is implied by this implicator
|
||||
* @param {Actor} actor
|
||||
* @param {string} permission
|
||||
* @returns
|
||||
*/
|
||||
async check (actor, permission) {
|
||||
return await this.checker(actor, permission);
|
||||
}
|
||||
}
|
||||
|
||||
class PermissionUtil {
|
||||
static unescape_permission_component (component) {
|
||||
let unescaped_str = '';
|
||||
@@ -142,6 +173,7 @@ class PermissionService extends BaseService {
|
||||
this._register_commands(this.services.get('commands'));
|
||||
|
||||
this._permission_rewriters = [];
|
||||
this._permission_implicators = [];
|
||||
}
|
||||
|
||||
async _rewrite_permission (permission) {
|
||||
@@ -152,8 +184,16 @@ class PermissionService extends BaseService {
|
||||
return permission;
|
||||
}
|
||||
|
||||
async check () {
|
||||
const ld = (Context.get('logdent') ?? 0) + 1;
|
||||
return await Context.get().sub({ logdent: ld }).arun(async () => {
|
||||
const res = await this.check__(...arguments);
|
||||
// this.log.noticeme('RETURN ' + res);
|
||||
return res;
|
||||
});
|
||||
}
|
||||
|
||||
async check (actor, permission) {
|
||||
async check__ (actor, permission) {
|
||||
permission = await this._rewrite_permission(permission);
|
||||
|
||||
this.log.info(`checking permission ${permission} for actor ${actor.uid}`, {
|
||||
@@ -162,30 +202,87 @@ class PermissionService extends BaseService {
|
||||
});
|
||||
// For now we're only checking driver permissions, and users have all of them
|
||||
if ( actor.type instanceof UserActorType ) {
|
||||
return {};
|
||||
return await this.check_user_permission(actor, permission);
|
||||
}
|
||||
|
||||
if ( actor.type instanceof AccessTokenActorType ) {
|
||||
// Authorizer must have permission
|
||||
const authorizer_permission = await this.check(actor.type.authorizer, permission);
|
||||
if ( ! authorizer_permission ) return false;
|
||||
|
||||
return await this.check_access_token_permission(
|
||||
actor.type.authorizer, actor.type.token, permission
|
||||
);
|
||||
}
|
||||
|
||||
// Prevent undefined behaviour
|
||||
if ( ! (actor.type instanceof AppUnderUserActorType) ) {
|
||||
throw new Error('actor must be an app under a user');
|
||||
if ( actor.type instanceof AppUnderUserActorType ) {
|
||||
// NEXT:
|
||||
const app_uid = actor.type.app.uid;
|
||||
const user_actor = actor.get_related_actor(UserActorType);
|
||||
const user_has_permission = await this.check_user_permission(user_actor, permission);
|
||||
if ( ! user_has_permission ) return undefined;
|
||||
|
||||
return await this.check_user_app_permission(actor, app_uid, permission);
|
||||
}
|
||||
|
||||
// Now it's an app under a user
|
||||
const app_uid = actor.type.app.uid;
|
||||
return await this.check_user_app_permission(actor, app_uid, permission);
|
||||
throw new Error('unrecognized actor type');
|
||||
}
|
||||
|
||||
// TODO: context meta for cycle detection
|
||||
async check_user_permission (actor, permission) {
|
||||
permission = await this._rewrite_permission(permission);
|
||||
const parent_perms = this.get_parent_permissions(permission);
|
||||
|
||||
// Check implicit permissions
|
||||
for ( const parent_perm of parent_perms ) {
|
||||
if ( implicit_user_permissions[parent_perm] ) {
|
||||
return implicit_user_permissions[parent_perm];
|
||||
}
|
||||
}
|
||||
|
||||
for ( const implicator of this._permission_implicators ) {
|
||||
if ( ! implicator.matches(permission) ) continue;
|
||||
const implied = await implicator.check(actor, permission);
|
||||
if ( implied ) return implied;
|
||||
}
|
||||
|
||||
// Check permissions granted by other users
|
||||
let sql_perm = parent_perms.map((perm) =>
|
||||
`\`permission\` = ?`).join(' OR ');
|
||||
if ( parent_perms.length > 1 ) sql_perm = '(' + sql_perm + ')';
|
||||
|
||||
// SELECT permission
|
||||
const rows = await this.db.read(
|
||||
'SELECT * FROM `user_to_user_permissions` ' +
|
||||
'WHERE `holder_user_id` = ? AND ' +
|
||||
sql_perm,
|
||||
[
|
||||
actor.type.user.id,
|
||||
...parent_perms,
|
||||
]
|
||||
);
|
||||
|
||||
// Return the first matching permission where the
|
||||
// issuer also has the permission granted
|
||||
for ( const row of rows ) {
|
||||
const issuer_actor = new Actor({
|
||||
type: new UserActorType({
|
||||
user: await get_user({ id: row.issuer_user_id }),
|
||||
}),
|
||||
});
|
||||
|
||||
const issuer_perm = await this.check(issuer_actor, row.permission);
|
||||
|
||||
if ( ! issuer_perm ) continue;
|
||||
|
||||
return row.extra;
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
async check_access_token_permission (authorizer, token, permission) {
|
||||
// Authorizer must have permission
|
||||
const authorizer_permission = await this.check(authorizer, permission);
|
||||
if ( ! authorizer_permission ) return false;
|
||||
|
||||
const rows = await this.db.read(
|
||||
'SELECT * FROM `access_token_permissions` ' +
|
||||
'WHERE `token_uid` = ? AND `permission` = ?',
|
||||
@@ -208,18 +305,7 @@ class PermissionService extends BaseService {
|
||||
if ( ! app ) app = await get_app({ name: app_uid });
|
||||
const app_id = app.id;
|
||||
|
||||
const parent_perms = [];
|
||||
{
|
||||
// We don't use PermissionUtil.split here because it unescapes
|
||||
// components; we want to keep the components escaped for matching.
|
||||
const parts = permission.split(':');
|
||||
|
||||
// Add sub-permissions
|
||||
for ( let i = 1 ; i < parts.length ; i++ ) {
|
||||
parent_perms.push(parts.slice(0, i + 1).join(':'));
|
||||
}
|
||||
}
|
||||
parent_perms.reverse();
|
||||
const parent_perms = this.get_parent_permissions(permission);
|
||||
|
||||
for ( const permission of parent_perms ) {
|
||||
// Check hardcoded permissions
|
||||
@@ -394,6 +480,107 @@ class PermissionService extends BaseService {
|
||||
);
|
||||
}
|
||||
|
||||
async grant_user_user_permission (actor, username, permission, extra = {}, meta) {
|
||||
permission = await this._rewrite_permission(permission);
|
||||
const user = await get_user({ username });
|
||||
if ( ! user ) {
|
||||
throw new Error('user not found');
|
||||
}
|
||||
|
||||
// Don't allow granting permissions to yourself
|
||||
if ( user.id === actor.type.user.id ) {
|
||||
throw new Error('cannot grant permissions to yourself');
|
||||
}
|
||||
|
||||
// UPSERT permission
|
||||
await this.db.write(
|
||||
'INSERT INTO `user_to_user_permissions` (`holder_user_id`, `issuer_user_id`, `permission`, `extra`) ' +
|
||||
'VALUES (?, ?, ?, ?) ' +
|
||||
this.db.case({
|
||||
mysql: 'ON DUPLICATE KEY UPDATE `extra` = ?',
|
||||
otherwise: 'ON CONFLICT(`holder_user_id`, `issuer_user_id`, `permission`) DO UPDATE SET `extra` = ?',
|
||||
}),
|
||||
[
|
||||
user.id,
|
||||
actor.type.user.id,
|
||||
permission,
|
||||
JSON.stringify(extra),
|
||||
JSON.stringify(extra),
|
||||
]
|
||||
);
|
||||
|
||||
// INSERT audit table
|
||||
await this.db.write(
|
||||
'INSERT INTO `audit_user_to_user_permissions` (' +
|
||||
'`holder_user_id`, `holder_user_id_keep`, `issuer_user_id`, `issuer_user_id_keep`, ' +
|
||||
'`permission`, `action`, `reason`) ' +
|
||||
'VALUES (?, ?, ?, ?, ?, ?, ?)',
|
||||
[
|
||||
user.id,
|
||||
user.id,
|
||||
actor.type.user.id,
|
||||
actor.type.user.id,
|
||||
permission,
|
||||
'grant',
|
||||
meta?.reason || 'granted via PermissionService',
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
async revoke_user_user_permission (actor, username, permission, meta) {
|
||||
permission = await this._rewrite_permission(permission);
|
||||
|
||||
const user = await get_user({ username });
|
||||
if ( ! user ) {
|
||||
throw new Error('user not found');
|
||||
}
|
||||
|
||||
// DELETE permission
|
||||
await this.db.write(
|
||||
'DELETE FROM `user_to_user_permissions` ' +
|
||||
'WHERE `holder_user_id` = ? AND `issuer_user_id` = ? AND `permission` = ?',
|
||||
[
|
||||
user.id,
|
||||
actor.type.user.id,
|
||||
permission,
|
||||
]
|
||||
);
|
||||
|
||||
// INSERT audit table
|
||||
await this.db.write(
|
||||
'INSERT INTO `audit_user_to_user_permissions` (' +
|
||||
'`holder_user_id`, `holder_user_id_keep`, `issuer_user_id`, `issuer_user_id_keep`, ' +
|
||||
'`permission`, `action`, `reason`) ' +
|
||||
'VALUES (?, ?, ?, ?, ?, ?, ?)',
|
||||
[
|
||||
user.id,
|
||||
user.id,
|
||||
actor.type.user.id,
|
||||
actor.type.user.id,
|
||||
permission,
|
||||
'revoke',
|
||||
meta?.reason || 'revoked via PermissionService',
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
get_parent_permissions (permission) {
|
||||
const parent_perms = [];
|
||||
{
|
||||
// We don't use PermissionUtil.split here because it unescapes
|
||||
// components; we want to keep the components escaped for matching.
|
||||
const parts = permission.split(':');
|
||||
|
||||
// Add sub-permissions
|
||||
for ( let i = 0 ; i < parts.length ; i++ ) {
|
||||
parent_perms.push(parts.slice(0, i + 1).join(':'));
|
||||
}
|
||||
}
|
||||
parent_perms.reverse();
|
||||
return parent_perms;
|
||||
}
|
||||
|
||||
|
||||
register_rewriter (translator) {
|
||||
if ( ! (translator instanceof PermissionRewriter) ) {
|
||||
throw new Error('translator must be a PermissionRewriter');
|
||||
@@ -402,6 +589,14 @@ class PermissionService extends BaseService {
|
||||
this._permission_rewriters.push(translator);
|
||||
}
|
||||
|
||||
register_implicator (implicator) {
|
||||
if ( ! (implicator instanceof PermissionImplicator) ) {
|
||||
throw new Error('implicator must be a PermissionImplicator');
|
||||
}
|
||||
|
||||
this._permission_implicators.push(implicator);
|
||||
}
|
||||
|
||||
_register_commands (commands) {
|
||||
commands.registerCommands('perms', [
|
||||
{
|
||||
@@ -425,6 +620,7 @@ class PermissionService extends BaseService {
|
||||
|
||||
module.exports = {
|
||||
PermissionRewriter,
|
||||
PermissionImplicator,
|
||||
PermissionUtil,
|
||||
PermissionService,
|
||||
};
|
||||
@@ -16,6 +16,8 @@
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
const { es_import_promise } = require("../../fun/dev-console-ui-utils");
|
||||
const { surrounding_box } = require("../../fun/dev-console-ui-utils");
|
||||
const { BaseDatabaseAccessService } = require("./BaseDatabaseAccessService");
|
||||
|
||||
class SqliteDatabaseAccessService extends BaseDatabaseAccessService {
|
||||
@@ -39,25 +41,102 @@ class SqliteDatabaseAccessService extends BaseDatabaseAccessService {
|
||||
|
||||
this.db = new Database(this.config.path);
|
||||
|
||||
// Database upgrade logic
|
||||
const TARGET_VERSION = 5;
|
||||
|
||||
if ( do_setup ) {
|
||||
this.log.noticeme(`SETUP: creating database at ${this.config.path}`);
|
||||
const sql_files = [
|
||||
'0001_create-tables.sql',
|
||||
'0002_add-default-apps.sql',
|
||||
'0003_user-permissions.sql',
|
||||
'0004_sessions.sql',
|
||||
'0005_background-apps.sql',
|
||||
'0006_update-apps.sql',
|
||||
'0007_sessions.sql',
|
||||
].map(p => path_.join(__dirname, 'sqlite_setup', p));
|
||||
const fs = require('fs');
|
||||
for ( const filename of sql_files ) {
|
||||
const basename = path_.basename(filename);
|
||||
this.log.noticeme(`applying ${basename}`);
|
||||
const contents = fs.readFileSync(filename, 'utf8');
|
||||
this.db.exec(contents);
|
||||
}
|
||||
await this.db.exec(`PRAGMA user_version = ${TARGET_VERSION};`);
|
||||
}
|
||||
|
||||
// Create the tables if they don't exist.
|
||||
const check =
|
||||
`SELECT name FROM sqlite_master WHERE type='table' AND name='fsentries'`;
|
||||
const rows = await this.db.prepare(check).all();
|
||||
if ( rows.length === 0 ) {
|
||||
throw new Error('it works');
|
||||
const [{ user_version }] = await this._read('PRAGMA user_version');
|
||||
this.log.info('database version: ' + user_version);
|
||||
|
||||
const upgrade_files = [];
|
||||
|
||||
if ( user_version <= 0 ) {
|
||||
upgrade_files.push('0003_user-permissions.sql');
|
||||
}
|
||||
|
||||
if ( user_version <= 1 ) {
|
||||
upgrade_files.push('0004_sessions.sql');
|
||||
}
|
||||
|
||||
if ( user_version <= 2 ) {
|
||||
upgrade_files.push('0005_background-apps.sql');
|
||||
}
|
||||
|
||||
if ( user_version <= 3 ) {
|
||||
upgrade_files.push('0006_update-apps.sql');
|
||||
}
|
||||
|
||||
if ( user_version <= 4 ) {
|
||||
upgrade_files.push('0007_sessions.sql');
|
||||
}
|
||||
|
||||
if ( upgrade_files.length > 0 ) {
|
||||
this.log.noticeme(`Database out of date: ${this.config.path}`);
|
||||
this.log.noticeme(`UPGRADING DATABASE: ${user_version} -> ${TARGET_VERSION}`);
|
||||
this.log.noticeme(`${upgrade_files.length} .sql files to apply`);
|
||||
|
||||
const sql_files = upgrade_files.map(
|
||||
p => path_.join(__dirname, 'sqlite_setup', p)
|
||||
);
|
||||
const fs = require('fs');
|
||||
for ( const filename of sql_files ) {
|
||||
const basename = path_.basename(filename);
|
||||
this.log.noticeme(`applying ${basename}`);
|
||||
const contents = fs.readFileSync(filename, 'utf8');
|
||||
this.db.exec(contents);
|
||||
}
|
||||
|
||||
// Update version number
|
||||
await this.db.exec(`PRAGMA user_version = ${TARGET_VERSION};`);
|
||||
|
||||
// Add sticky notification
|
||||
this.database_update_notice = () => {
|
||||
const lines = [
|
||||
`Database has been updated!`,
|
||||
`Current version: ${TARGET_VERSION}`,
|
||||
`Type sqlite:dismiss to dismiss this message`,
|
||||
];
|
||||
surrounding_box('33;1', lines);
|
||||
return lines;
|
||||
};
|
||||
|
||||
(async () => {
|
||||
await es_import_promise;
|
||||
const svc_devConsole = this.services.get('dev-console');
|
||||
svc_devConsole.add_widget(this.database_update_notice);
|
||||
})();
|
||||
}
|
||||
|
||||
const svc_serverHealth = this.services.get('server-health');
|
||||
|
||||
svc_serverHealth.add_check('sqlite', async () => {
|
||||
const [{ user_version }] = await this._requireRead('PRAGMA user_version');
|
||||
if ( user_version !== TARGET_VERSION ) {
|
||||
throw new Error(
|
||||
`Database version mismatch: expected ${TARGET_VERSION}, ` +
|
||||
`got ${user_version}`);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async _read (query, params = []) {
|
||||
@@ -148,6 +227,19 @@ class SqliteDatabaseAccessService extends BaseDatabaseAccessService {
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
id: 'dismiss',
|
||||
description: 'dismiss the database update notice',
|
||||
handler: async (_, log) => {
|
||||
const svc_devConsole = this.services.get('dev-console');
|
||||
if ( ! svc_devConsole ) return;
|
||||
if ( ! this.database_update_notice ) return;
|
||||
svc_devConsole.remove_widget(this.database_update_notice);
|
||||
const lines = this.database_update_notice();
|
||||
for ( const line of lines ) log.log(line);
|
||||
this.database_update_notice = null;
|
||||
}
|
||||
}
|
||||
])
|
||||
}
|
||||
}
|
||||
|
||||
@@ -120,7 +120,10 @@ CREATE TABLE `kv` (
|
||||
`value` text,
|
||||
|
||||
-- 0016
|
||||
`migrated` tinyint(1) DEFAULT '0'
|
||||
`migrated` tinyint(1) DEFAULT '0',
|
||||
|
||||
-- 0019
|
||||
UNIQUE (user_id, app, kkey_hash)
|
||||
);
|
||||
|
||||
CREATE TABLE `subdomains` (
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
CREATE TABLE `user_to_user_permissions` (
|
||||
"issuer_user_id" INTEGER NOT NULL,
|
||||
"holder_user_id" INTEGER NOT NULL,
|
||||
"permission" TEXT NOT NULL,
|
||||
"extra" JSON DEFAULT NULL,
|
||||
|
||||
FOREIGN KEY("issuer_user_id") REFERENCES "user" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
|
||||
FOREIGN KEY("holder_user_id") REFERENCES "user" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
|
||||
PRIMARY KEY ("issuer_user_id", "holder_user_id", "permission")
|
||||
);
|
||||
|
||||
CREATE TABLE "audit_user_to_user_permissions" (
|
||||
"id" INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
|
||||
"issuer_user_id" INTEGER NOT NULL,
|
||||
"issuer_user_id_keep" INTEGER DEFAULT NULL,
|
||||
|
||||
"holder_user_id" INTEGER NOT NULL,
|
||||
"holder_user_id_keep" INTEGER DEFAULT NULL,
|
||||
|
||||
"permission" TEXT NOT NULL,
|
||||
"extra" JSON DEFAULT NULL,
|
||||
|
||||
"action" TEXT DEFAULT NULL,
|
||||
"reason" TEXT DEFAULT NULL,
|
||||
|
||||
"created_at" TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
FOREIGN KEY("issuer_user_id") REFERENCES "user" ("id") ON DELETE SET NULL ON UPDATE CASCADE,
|
||||
FOREIGN KEY("holder_user_id") REFERENCES "user" ("id") ON DELETE SET NULL ON UPDATE CASCADE
|
||||
);
|
||||
@@ -0,0 +1,7 @@
|
||||
CREATE TABLE `sessions` (
|
||||
"id" INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
"user_id" INTEGER NOT NULL,
|
||||
"uuid" TEXT NOT NULL,
|
||||
"meta" JSON DEFAULT NULL,
|
||||
FOREIGN KEY("user_id") REFERENCES "user" ("id") ON DELETE CASCADE ON UPDATE CASCADE
|
||||
);
|
||||
@@ -0,0 +1 @@
|
||||
ALTER TABLE apps ADD COLUMN "background" BOOLEAN DEFAULT 0;
|
||||
@@ -0,0 +1,5 @@
|
||||
UPDATE `apps` SET `index_url` = 'https://builtins.namespaces.puter.com/terminal' WHERE `name` = 'terminal';
|
||||
|
||||
INSERT INTO `apps` (`uid`, `owner_user_id`, `name`, `title`, `description`, `godmode`, `background`, `maximize_on_start`, `index_url`, `approved_for_listing`, `approved_for_opening_items`, `approved_for_incentive_program`, `timestamp`, `last_review`, `tags`, `app_owner`) VALUES (
|
||||
'129e4bfb-4c8a-47e0-bec2-0279c21ace06', 1,
|
||||
'phoenix','Phoenix Shell','',0,1,1,'https://builtins.namespaces.puter.com/phoenix',1,0,0,'2022-08-16 01:28:47',NULL,'productivity',NULL);
|
||||
@@ -0,0 +1,2 @@
|
||||
ALTER TABLE `sessions` ADD COLUMN "created_at" INTEGER DEFAULT 0;
|
||||
ALTER TABLE `sessions` ADD COLUMN "last_activity" INTEGER DEFAULT 0;
|
||||
@@ -55,7 +55,7 @@ class DBKVStore extends BaseImplementation {
|
||||
[ user.id, key_hash ]
|
||||
);
|
||||
|
||||
return kv[0] ? { key: kv[0].key, value: kv[0].value } : null;
|
||||
return kv[0]?.value ?? null;
|
||||
},
|
||||
set: async function ({ key, value }) {
|
||||
const actor = this.context.get('actor');
|
||||
@@ -84,15 +84,27 @@ class DBKVStore extends BaseImplementation {
|
||||
const db = this.services.get('database').get(DB_WRITE, 'kvstore');
|
||||
const key_hash = this.modules.murmurhash.v3(key);
|
||||
|
||||
await db.write(
|
||||
`INSERT INTO kv
|
||||
(user_id, app, kkey_hash, kkey, value)
|
||||
VALUES
|
||||
(?, ?, ?, ?, ?)
|
||||
ON DUPLICATE KEY UPDATE
|
||||
value = ?`,
|
||||
[ user.id, app?.uid ?? 'global', key_hash, key, value, value ]
|
||||
);
|
||||
try {
|
||||
await db.write(
|
||||
`INSERT INTO kv (user_id, app, kkey_hash, kkey, value)
|
||||
VALUES (?, ?, ?, ?, ?) ` +
|
||||
db.case({
|
||||
mysql: 'ON DUPLICATE KEY UPDATE value = ?',
|
||||
sqlite: 'ON CONFLICT(user_id, app, kkey_hash) DO UPDATE SET value = excluded.value',
|
||||
}),
|
||||
[
|
||||
user.id, app?.uid ?? 'global', key_hash, key, value,
|
||||
...db.case({ mysql: [value], otherwise: [] }),
|
||||
]
|
||||
);
|
||||
} catch (e) {
|
||||
// if ( e.code !== 'SQLITE_ERROR' && e.code !== 'SQLITE_CONSTRAINT_PRIMARYKEY' ) throw e;
|
||||
// The "ON CONFLICT" clause isn't currently working.
|
||||
await db.write(
|
||||
`UPDATE kv SET value = ? WHERE user_id=? AND app=? AND kkey_hash=?`,
|
||||
[ value, user.id, app?.uid ?? 'global', key_hash ]
|
||||
);
|
||||
}
|
||||
|
||||
return true;
|
||||
},
|
||||
|
||||
@@ -159,7 +159,11 @@ class DevLogger {
|
||||
log_lvl, crumbs, message, fields, objects,
|
||||
);
|
||||
}
|
||||
this.log(stringify_log_entry({
|
||||
const ld = Context.get('logdent', { allow_fallback: true })
|
||||
const prefix = globalThis.dev_console_indent_on
|
||||
? Array(ld ?? 0).fill(' ').join('')
|
||||
: '';
|
||||
this.log(prefix + stringify_log_entry({
|
||||
log_lvl, crumbs, message, fields, objects,
|
||||
}));
|
||||
}
|
||||
|
||||
@@ -19,14 +19,18 @@
|
||||
const BaseService = require("../BaseService");
|
||||
const { SECOND } = require("../../util/time");
|
||||
const { parse_meminfo } = require("../../util/linux");
|
||||
const { asyncSafeSetInterval } = require("../../util/promise");
|
||||
const { asyncSafeSetInterval, TeePromise } = require("../../util/promise");
|
||||
|
||||
class ServerHealthService extends BaseService {
|
||||
static MODULES = {
|
||||
fs: require('fs'),
|
||||
}
|
||||
_construct () {
|
||||
this.checks_ = [];
|
||||
this.failures_ = [];
|
||||
}
|
||||
async _init () {
|
||||
const ram_poll_interval = 10 * SECOND;
|
||||
this.init_service_checks_();
|
||||
|
||||
/*
|
||||
There's an interesting thread here:
|
||||
@@ -53,7 +57,7 @@ class ServerHealthService extends BaseService {
|
||||
return;
|
||||
}
|
||||
|
||||
asyncSafeSetInterval(async () => {
|
||||
this.add_check('ram-usage', async () => {
|
||||
const meminfo_text = await this.modules.fs.promises.readFile(
|
||||
'/proc/meminfo', 'utf8'
|
||||
);
|
||||
@@ -69,11 +73,46 @@ class ServerHealthService extends BaseService {
|
||||
if ( meminfo.MemAvailable < min_available_KiB ) {
|
||||
svc_alarm.create('low-available-memory', 'Low available memory', alarm_fields);
|
||||
}
|
||||
}, ram_poll_interval, null,{
|
||||
});
|
||||
}
|
||||
|
||||
init_service_checks_ () {
|
||||
const svc_alarm = this.services.get('alarm');
|
||||
asyncSafeSetInterval(async () => {
|
||||
const check_failures = [];
|
||||
for ( const { name, fn } of this.checks_ ) {
|
||||
const p_timeout = new TeePromise();
|
||||
const timeout = setTimeout(() => {
|
||||
p_timeout.reject(new Error('Health check timed out'));
|
||||
}, 5 * SECOND);
|
||||
try {
|
||||
await Promise.race([
|
||||
fn(),
|
||||
p_timeout,
|
||||
]);
|
||||
clearTimeout(timeout);
|
||||
} catch ( err ) {
|
||||
// Trigger an alarm if this check isn't already in the failure list
|
||||
|
||||
if ( this.failures_.some(v => v.name === name) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
svc_alarm.create(
|
||||
'health-check-failure',
|
||||
`Health check ${name} failed`,
|
||||
{ error: err }
|
||||
);
|
||||
check_failures.push({ name });
|
||||
}
|
||||
}
|
||||
|
||||
this.failures_ = check_failures;
|
||||
}, 10 * SECOND, null, {
|
||||
onBehindSchedule: (drift) => {
|
||||
svc_alarm.create(
|
||||
'ram-usage-poll-behind-schedule',
|
||||
'RAM usage poll is behind schedule',
|
||||
'health-checks-behind-schedule',
|
||||
'Health checks are behind schedule',
|
||||
{ drift }
|
||||
);
|
||||
}
|
||||
@@ -83,6 +122,18 @@ class ServerHealthService extends BaseService {
|
||||
async get_stats () {
|
||||
return { ...this.stats_ };
|
||||
}
|
||||
|
||||
add_check (name, fn) {
|
||||
this.checks_.push({ name, fn });
|
||||
}
|
||||
|
||||
get_status () {
|
||||
const failures = this.failures_.map(v => v.name);
|
||||
return {
|
||||
ok: failures.length === 0,
|
||||
...(failures.length ? { failed: failures } : {}),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { ServerHealthService };
|
||||
@@ -34,18 +34,48 @@ class MonthlyUsageService extends BaseService {
|
||||
|
||||
const maybe_app_id = actor.type.app?.id;
|
||||
|
||||
if ( this.db.case({ sqlite: true, otherwise: false }) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
const vals =
|
||||
[
|
||||
year, month, key, actor.type.user.id, maybe_app_id, JSON.stringify(extra),
|
||||
...this.db.case({ mysql: [JSON.stringify(extra)], otherwise: [] }),
|
||||
]
|
||||
console.log('VALS', vals);
|
||||
|
||||
// UPSERT increment count
|
||||
await this.db.write(
|
||||
'INSERT INTO `service_usage_monthly` (`year`, `month`, `key`, `count`, `user_id`, `app_id`, `extra`) ' +
|
||||
'VALUES (?, ?, ?, 1, ?, ?, ?) ' +
|
||||
'ON DUPLICATE KEY UPDATE `count` = `count` + 1',
|
||||
[
|
||||
year, month, key,
|
||||
actor.type.user?.id || null,
|
||||
maybe_app_id || null,
|
||||
JSON.stringify(extra)
|
||||
]
|
||||
);
|
||||
try {
|
||||
await this.db.write(
|
||||
'INSERT INTO `service_usage_monthly` (`year`, `month`, `key`, `count`, `user_id`, `app_id`, `extra`) ' +
|
||||
'VALUES (?, ?, ?, 1, ?, ?, ?) ' +
|
||||
this.db.case({
|
||||
mysql: 'ON DUPLICATE KEY UPDATE `count` = `count` + 1, `extra` = ?',
|
||||
sqlite: ' ',
|
||||
// sqlite: 'ON CONFLICT(`year`, `month`, `key`, `user_id`, `app_id`) ' +
|
||||
// 'DO UPDATE SET `count` = `count` + 1 AND `extra` = ?',
|
||||
}),
|
||||
[
|
||||
year, month, key, actor.type.user.id, maybe_app_id ?? null, JSON.stringify(extra),
|
||||
...this.db.case({ mysql: [JSON.stringify(extra)], otherwise: [] }),
|
||||
]
|
||||
);
|
||||
} catch (e) {
|
||||
// if ( e.code !== 'SQLITE_ERROR' && e.code !== 'SQLITE_CONSTRAINT_PRIMARYKEY' ) throw e;
|
||||
// The "ON CONFLICT" clause isn't currently working.
|
||||
await this.db.write(
|
||||
'UPDATE `service_usage_monthly` ' +
|
||||
'SET `count` = `count` + 1, `extra` = ? ' +
|
||||
'WHERE `year` = ? AND `month` = ? AND `key` = ? ' +
|
||||
'AND `user_id` = ? AND `app_id` = ?',
|
||||
[
|
||||
JSON.stringify(extra),
|
||||
year, month, key, actor.type.user.id, maybe_app_id,
|
||||
]
|
||||
);
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
async check (actor, specifiers) {
|
||||
|
||||
@@ -21,8 +21,11 @@ const path_ = require('path');
|
||||
const fs_ = require('fs');
|
||||
|
||||
const generate_puter_page_html = ({
|
||||
env,
|
||||
|
||||
manifest,
|
||||
gui_path,
|
||||
use_bundled_gui,
|
||||
|
||||
app_origin,
|
||||
api_origin,
|
||||
@@ -49,6 +52,12 @@ const generate_puter_page_html = ({
|
||||
gui_origin: app_origin,
|
||||
};
|
||||
|
||||
const asset_dir = env === 'dev'
|
||||
? '/src' : '/dist' ;
|
||||
// const asset_dir = '/dist';
|
||||
|
||||
const bundled = env != 'dev' || use_bundled_gui;
|
||||
|
||||
return `<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
|
||||
@@ -64,7 +73,10 @@ const generate_puter_page_html = ({
|
||||
<meta property="og:type" content="website">
|
||||
<meta property="og:title" content="${e(title)}">
|
||||
<meta property="og:description" content="${e((short_description).replace(/\n/g, " "))}">
|
||||
<meta property="og:image" content="/dist/images/screenshot.png">
|
||||
<meta property="og:image" content="${asset_dir}/images/screenshot.png">
|
||||
|
||||
<!-- disable iframes -->
|
||||
<meta http-equiv="X-Frame-Options" content="sameorigin">
|
||||
|
||||
<!-- Twitter meta tags -->
|
||||
<meta name="twitter:card" content="summary_large_image">
|
||||
@@ -72,33 +84,33 @@ const generate_puter_page_html = ({
|
||||
<meta property="twitter:url" content="${app_origin}">
|
||||
<meta name="twitter:title" content="${e(title)}">
|
||||
<meta name="twitter:description" content="${e((short_description).replace(/\n/g, " "))}">
|
||||
<meta name="twitter:image" content="/dist/images/screenshot.png">
|
||||
<meta name="twitter:image" content="${asset_dir}/images/screenshot.png">
|
||||
|
||||
<!-- favicons -->
|
||||
<link rel="apple-touch-icon" sizes="57x57" href="/dist/favicons/apple-icon-57x57.png">
|
||||
<link rel="apple-touch-icon" sizes="60x60" href="/dist/favicons/apple-icon-60x60.png">
|
||||
<link rel="apple-touch-icon" sizes="72x72" href="/dist/favicons/apple-icon-72x72.png">
|
||||
<link rel="apple-touch-icon" sizes="76x76" href="/dist/favicons/apple-icon-76x76.png">
|
||||
<link rel="apple-touch-icon" sizes="114x114" href="/dist/favicons/apple-icon-114x114.png">
|
||||
<link rel="apple-touch-icon" sizes="120x120" href="/dist/favicons/apple-icon-120x120.png">
|
||||
<link rel="apple-touch-icon" sizes="144x144" href="/dist/favicons/apple-icon-144x144.png">
|
||||
<link rel="apple-touch-icon" sizes="152x152" href="/dist/favicons/apple-icon-152x152.png">
|
||||
<link rel="apple-touch-icon" sizes="180x180" href="/dist/favicons/apple-icon-180x180.png">
|
||||
<link rel="icon" type="image/png" sizes="192x192" href="/dist/favicons/android-icon-192x192.png">
|
||||
<link rel="icon" type="image/png" sizes="32x32" href="/dist/favicons/favicon-32x32.png">
|
||||
<link rel="icon" type="image/png" sizes="96x96" href="/dist/favicons/favicon-96x96.png">
|
||||
<link rel="icon" type="image/png" sizes="16x16" href="/dist/favicons/favicon-16x16.png">
|
||||
<link rel="manifest" href="/dist/manifest.json">
|
||||
<link rel="apple-touch-icon" sizes="57x57" href="${asset_dir}/favicons/apple-icon-57x57.png">
|
||||
<link rel="apple-touch-icon" sizes="60x60" href="${asset_dir}/favicons/apple-icon-60x60.png">
|
||||
<link rel="apple-touch-icon" sizes="72x72" href="${asset_dir}/favicons/apple-icon-72x72.png">
|
||||
<link rel="apple-touch-icon" sizes="76x76" href="${asset_dir}/favicons/apple-icon-76x76.png">
|
||||
<link rel="apple-touch-icon" sizes="114x114" href="${asset_dir}/favicons/apple-icon-114x114.png">
|
||||
<link rel="apple-touch-icon" sizes="120x120" href="${asset_dir}/favicons/apple-icon-120x120.png">
|
||||
<link rel="apple-touch-icon" sizes="144x144" href="${asset_dir}/favicons/apple-icon-144x144.png">
|
||||
<link rel="apple-touch-icon" sizes="152x152" href="${asset_dir}/favicons/apple-icon-152x152.png">
|
||||
<link rel="apple-touch-icon" sizes="180x180" href="${asset_dir}/favicons/apple-icon-180x180.png">
|
||||
<link rel="icon" type="image/png" sizes="192x192" href="${asset_dir}/favicons/android-icon-192x192.png">
|
||||
<link rel="icon" type="image/png" sizes="32x32" href="${asset_dir}/favicons/favicon-32x32.png">
|
||||
<link rel="icon" type="image/png" sizes="96x96" href="${asset_dir}/favicons/favicon-96x96.png">
|
||||
<link rel="icon" type="image/png" sizes="16x16" href="${asset_dir}/favicons/favicon-16x16.png">
|
||||
<link rel="manifest" href="${asset_dir}/manifest.json">
|
||||
<meta name="msapplication-TileColor" content="#ffffff">
|
||||
<meta name="msapplication-TileImage" content="/dist/favicons/ms-icon-144x144.png">
|
||||
<meta name="msapplication-TileImage" content="${asset_dir}/favicons/ms-icon-144x144.png">
|
||||
<meta name="theme-color" content="#ffffff">
|
||||
|
||||
<!-- Preload images when applicable -->
|
||||
<link rel="preload" as="image" href="/dist/images/wallpaper.webp">
|
||||
<link rel="preload" as="image" href="${asset_dir}/images/wallpaper.webp">
|
||||
|
||||
<!-- Files from JSON (may be empty) -->
|
||||
${
|
||||
(manifest?.css_paths
|
||||
((!bundled && manifest?.css_paths)
|
||||
? manifest.css_paths.map(path => `<link rel="stylesheet" href="${path}">\n`)
|
||||
: []).join('')
|
||||
}
|
||||
@@ -108,7 +120,12 @@ const generate_puter_page_html = ({
|
||||
<body>
|
||||
<script>window.puter_gui_enabled = true;</script>
|
||||
${
|
||||
(manifest?.lib_paths
|
||||
use_bundled_gui
|
||||
? `<script>window.gui_env = 'prod';</script>`
|
||||
: ''
|
||||
}
|
||||
${
|
||||
((!bundled && manifest?.lib_paths)
|
||||
? manifest.lib_paths.map(path => `<script type="text/javascript" src="${path}"></script>\n`)
|
||||
: []).join('')
|
||||
}
|
||||
@@ -117,7 +134,7 @@ const generate_puter_page_html = ({
|
||||
window.icons = {};
|
||||
|
||||
${(() => {
|
||||
if ( ! manifest ) return '';
|
||||
if ( !(!bundled && manifest) ) return '';
|
||||
const html = [];
|
||||
fs_.readdirSync(path_.join(gui_path, 'src/icons')).forEach(file => {
|
||||
// skip dotfiles
|
||||
@@ -138,16 +155,20 @@ const generate_puter_page_html = ({
|
||||
</script>
|
||||
|
||||
${
|
||||
(manifest?.js_paths
|
||||
((!bundled && manifest?.js_paths)
|
||||
? manifest.js_paths.map(path => `<script type="module" src="${path}"></script>\n`)
|
||||
: []).join('')
|
||||
}
|
||||
<!-- Load the GUI script -->
|
||||
<script ${ manifest.index ? ' type="module"' : ''} src="${manifest?.index ?? '/dist/gui.js'}"></script>
|
||||
<script ${ !bundled ? ' type="module"' : ''} src="${(!bundled && manifest?.index) || '/dist/gui.js'}"></script>
|
||||
<!-- Initialize GUI when document is loaded -->
|
||||
<script>
|
||||
window.addEventListener('load', function() {
|
||||
gui(${JSON.stringify(gui_params)});
|
||||
gui(${
|
||||
// TODO: override JSON.stringify to ALWAYS to this...
|
||||
// this should be an opt-OUT, not an opt-IN!
|
||||
JSON.stringify(gui_params).replace(/</g, '\\u003c')
|
||||
});
|
||||
});
|
||||
</script>
|
||||
<div id="templates" style="display: none;"></div>
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
let memoized_common_template_vars_ = null;
|
||||
const get_common_template_vars = () => {
|
||||
const path_ = require('path');
|
||||
if ( memoized_common_template_vars_ !== null ) {
|
||||
return memoized_common_template_vars_;
|
||||
}
|
||||
|
||||
const code_root = path_.resolve(__dirname, '../../');
|
||||
|
||||
memoized_common_template_vars_ = {
|
||||
code_root,
|
||||
};
|
||||
|
||||
return memoized_common_template_vars_;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
get_common_template_vars,
|
||||
};
|
||||
@@ -0,0 +1,4 @@
|
||||
node_modules/
|
||||
dist/
|
||||
release/
|
||||
*.tar
|
||||
@@ -0,0 +1,661 @@
|
||||
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||
Version 3, 19 November 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU Affero General Public License is a free, copyleft license for
|
||||
software and other kinds of works, specifically designed to ensure
|
||||
cooperation with the community in the case of network server software.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
our General Public Licenses are intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
Developers that use our General Public Licenses protect your rights
|
||||
with two steps: (1) assert copyright on the software, and (2) offer
|
||||
you this License which gives you legal permission to copy, distribute
|
||||
and/or modify the software.
|
||||
|
||||
A secondary benefit of defending all users' freedom is that
|
||||
improvements made in alternate versions of the program, if they
|
||||
receive widespread use, become available for other developers to
|
||||
incorporate. Many developers of free software are heartened and
|
||||
encouraged by the resulting cooperation. However, in the case of
|
||||
software used on network servers, this result may fail to come about.
|
||||
The GNU General Public License permits making a modified version and
|
||||
letting the public access it on a server without ever releasing its
|
||||
source code to the public.
|
||||
|
||||
The GNU Affero General Public License is designed specifically to
|
||||
ensure that, in such cases, the modified source code becomes available
|
||||
to the community. It requires the operator of a network server to
|
||||
provide the source code of the modified version running there to the
|
||||
users of that server. Therefore, public use of a modified version, on
|
||||
a publicly accessible server, gives the public access to the source
|
||||
code of the modified version.
|
||||
|
||||
An older license, called the Affero General Public License and
|
||||
published by Affero, was designed to accomplish similar goals. This is
|
||||
a different license, not a version of the Affero GPL, but Affero has
|
||||
released a new version of the Affero GPL which permits relicensing under
|
||||
this license.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU Affero General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Remote Network Interaction; Use with the GNU General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, if you modify the
|
||||
Program, your modified version must prominently offer all users
|
||||
interacting with it remotely through a computer network (if your version
|
||||
supports such interaction) an opportunity to receive the Corresponding
|
||||
Source of your version by providing access to the Corresponding Source
|
||||
from a network server at no charge, through some standard or customary
|
||||
means of facilitating copying of software. This Corresponding Source
|
||||
shall include the Corresponding Source for any work covered by version 3
|
||||
of the GNU General Public License that is incorporated pursuant to the
|
||||
following paragraph.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the work with which it is combined will remain governed by version
|
||||
3 of the GNU General Public License.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU Affero General Public License from time to time. Such new versions
|
||||
will be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU Affero General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU Affero General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU Affero General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as published
|
||||
by the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If your software can interact with users remotely through a computer
|
||||
network, you should also make sure that it provides a way for users to
|
||||
get its source. For example, if your program is a web application, its
|
||||
interface could display a "Source" link that leads users to an archive
|
||||
of the code. There are many ways you could offer source, and different
|
||||
solutions will be better for different programs; see section 13 for the
|
||||
specific requirements.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU AGPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
@@ -0,0 +1,54 @@
|
||||
<h2 align="center">Phoenix</h2>
|
||||
<h3 align="center">Puter's pure-javascript shell</h3>
|
||||
<h3 align="center"><img alt="" src="./doc/readme-gif.gif"></h3>
|
||||
<hr>
|
||||
|
||||
`phoenix` is a pure-javascript shell built for [puter.com](https://puter.com).
|
||||
Following the spirit of open-source initiatives we've seen like
|
||||
[SerenityOS](https://serenityos.org/),
|
||||
we've built much of the shell's functionality from scratch.
|
||||
Some interesting portions of this shell include:
|
||||
- A shell parser which produces a Concrete-Syntax-Tree
|
||||
- Pipeline constructs built on top of the [Streams API](https://developer.mozilla.org/en-US/docs/Web/API/Streams_API)
|
||||
- Platform support for Puter
|
||||
|
||||
The shell is a work in progress. The following improvements are considered in-scope:
|
||||
- Anything specified in [POSIX.1-2017 Chapter 2](https://pubs.opengroup.org/onlinepubs/9699919799.2018edition/utilities/V3_chap02.html)
|
||||
- UX improvements over traditional shells
|
||||
> examples include: readline syntax highlighting, hex view for binary streams
|
||||
- Platform support, so `phoenix` can run in more environments
|
||||
|
||||
## Running Phoenix
|
||||
|
||||
### In a Browser
|
||||
|
||||
You can use the [terminal on Puter](https://puter.com/app/terminal), including self-hosted installations.
|
||||
|
||||
### Running in Node
|
||||
|
||||
Under node.js Phoenix acts as a shell for your operating system.
|
||||
This is a work-in-progress and lots of things are not working
|
||||
yet. If you'd like to try it out you can run `src/main_cli.js`.
|
||||
Check [this issue](https://github.com/HeyPuter/phoenix/issues/14)
|
||||
for updated information on our progress.
|
||||
|
||||
## Testing
|
||||
|
||||
You can find our tests in the [test/](./test) directory.
|
||||
Testing is done with [mocha](https://www.npmjs.com/package/mocha).
|
||||
Make sure it's installed, then run:
|
||||
|
||||
```sh
|
||||
npm test
|
||||
```
|
||||
|
||||
## What's on the Roadmap?
|
||||
|
||||
We're looking to continue improving the shell and broaden its usefulness.
|
||||
Here are a few ideas we have for the future:
|
||||
|
||||
- local machine platform support
|
||||
> See [this issue](https://github.com/HeyPuter/phoenix/issues/14)
|
||||
- further support for the POSIX Command Language
|
||||
> Check our list of [missing features](doc/missing-posix.md)
|
||||
|
||||
Loaded 100 of 417 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user