Skip to content

Commit

Permalink
feat: sdk
Browse files Browse the repository at this point in the history
  • Loading branch information
hugomrdias committed Jul 29, 2022
1 parent 5cae9cd commit 305b2d3
Show file tree
Hide file tree
Showing 22 changed files with 657 additions and 148 deletions.
20 changes: 7 additions & 13 deletions packages/access-api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,7 @@
"description": "Auth API",
"type": "module",
"main": "dist/worker.js",
"types": "dist/src/index.d.ts",
"files": [
"dist/src/*.d.ts",
"dist/src/*.d.ts.map"
],
"typesVersions": {
"*": {
"*": [
"dist/src/*"
]
}
},
"private": "true",
"scripts": {
"lint": "tsc && eslint '**/*.{js,ts}' && prettier --check '**/*.{js,ts,md,yml,json}' --ignore-path ../../.gitignore",
"deploy": "wrangler publish",
Expand All @@ -37,6 +26,7 @@
"@web3-storage/w3access": "workspace:^",
"@web3-storage/worker-utils": "0.2.0-dev",
"multiformats": "^9.6.5",
"nanoid": "^4.0.0",
"toucan-js": "^2.6.0"
},
"devDependencies": {
Expand Down Expand Up @@ -74,7 +64,8 @@
"COMMITHASH": "readonly",
"BRANCH": "readonly",
"DEBUG": "readonly",
"ACCOUNTS": "writable"
"ACCOUNTS": "writable",
"VALIDATIONS": "writable"
}
},
"eslintIgnore": [
Expand All @@ -84,6 +75,9 @@
"docs"
],
"ava": {
"files": [
"test/**/*.test.js"
],
"ignoredByWatcher": [
"./dist/*"
]
Expand Down
2 changes: 2 additions & 0 deletions packages/access-api/src/bindings.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,15 @@ export {}

declare global {
const ACCOUNTS: KVNamespace
const VALIDATIONS: KVNamespace
}

export interface RouteContext {
params: Record<string, string>
log: Logging
keypair: SigningAuthority
config: typeof config
url: URL
}

export type Handler = (
Expand Down
3 changes: 3 additions & 0 deletions packages/access-api/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,14 @@ import { corsHeaders, preflight } from '@web3-storage/worker-utils/cors'
import { errorHandler } from '@web3-storage/worker-utils/error'
import { notFound } from '@web3-storage/worker-utils/response'
import { Router } from '@web3-storage/worker-utils/router'
import { validate } from './routes/validate.js'

/** @type Router<import('./bindings.js').RouteContext> */
const r = new Router({ onNotFound: notFound })
r.add('options', '*', preflight)
r.add('get', '/version', version)

r.add('get', '/validate', validate)
r.add('post', '/', async (request, env) => {
const server = Server.create({
id: env.keypair,
Expand Down
4 changes: 4 additions & 0 deletions packages/access-api/src/kvs/accounts.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@ export class Accounts {
* @param {import('@ucanto/interface').LinkedProof} proof
*/
async register(issuerDID, resourceDID, proof) {
const did = await this.get(issuerDID)
if (did) {
throw new Error(`did: ${issuerDID} already registered.`)
}
const account = `did:ipld:${proof}`
await this.kv.put(
issuerDID,
Expand Down
47 changes: 47 additions & 0 deletions packages/access-api/src/kvs/validations.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import * as UCAN from '@ipld/dag-ucan'

/**
* Validations
*/
export class Validations {
/**
*
* @param {KVNamespace} kv
*/
constructor(kv = VALIDATIONS) {
this.kv = kv
}

/**
*
* @param {string} delegation
*/
async create(delegation) {
// @ts-ignore
const ucan = UCAN.parse(delegation)
await this.kv.put(ucan.audience.did(), delegation, {
expirationTtl: 2 * 60,
})

return ucan
}

/**
* @param {string} did
*/
async get(did) {
const val = await this.kv.get(did)
if (!val) {
throw new Error('Validation not found')
}

return val
}

/**
* @param {string} did
*/
async delete(did) {
await this.kv.delete(did)
}
}
22 changes: 22 additions & 0 deletions packages/access-api/src/routes/validate.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { Validations } from '../kvs/validations.js'

/**
* @param {import('@web3-storage/worker-utils/router').ParsedRequest} req
* @param {import('../bindings.js').RouteContext} env
*/
export async function validate(req, env) {
const validations = new Validations()
if (req.query && req.query.ucan) {
await validations.create(req.query.ucan)

return new Response('Done')
}

if (req.query && req.query.did) {
const ucan = await validations.get(req.query.did)
await validations.delete(req.query.did)
return new Response(ucan)
}

throw new Error('needs ucan or did query')
}
81 changes: 0 additions & 81 deletions packages/access-api/src/ucanto/capabilities.js

This file was deleted.

19 changes: 9 additions & 10 deletions packages/access-api/src/ucanto/service.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import {
identityIdentify,
identityRegister,
identityValidate,
} from './capabilities.js'
} from '@web3-storage/w3access/capabilities'

/**
* @param {import('../bindings').RouteContext} ctx
Expand All @@ -29,21 +29,20 @@ export function service(ctx) {
})
.delegate()

// For testing
if (process.env.NODE_ENV === 'development') {
// console.log(
// '🚀 ~ file: service.js ~ line 34 ~ Server.UCAN.format(delegation.data)',
// Server.UCAN.format(delegation.data)
// )
const url = `${ctx.url.protocol}//${
ctx.url.host
}/validate?ucan=${UCAN.format(delegation.data)}`

// For testing
if (ctx.config.ENV === 'test') {
return {
delegation: UCAN.format(delegation.data),
delegation: url,
}
}

await sendEmail({
to: capability.caveats.as.replace('mailto:', ''),
ucan: UCAN.format(delegation.data),
url,
token: ctx.config.POSTMARK_TOKEN,
})
}
Expand All @@ -66,7 +65,7 @@ export function service(ctx) {
return result?.account
}),
},
// @ts-expect-error just for tests
// @ts-ignore
testing: {
pass() {
return 'test pass'
Expand Down
3 changes: 2 additions & 1 deletion packages/access-api/src/utils/context.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,5 +45,6 @@ export function getContext(event, params) {
)

const keypair = SigningAuthority.parse(config.PRIVATE_KEY)
return { params, log, keypair, config }
const url = new URL(event.request.url)
return { params, log, keypair, config, url }
}
4 changes: 2 additions & 2 deletions packages/access-api/src/utils/email.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/**
* @param {{ to: string; ucan: string; token: string }} opts
* @param {{ to: string; url: string; token: string }} opts
*/
export async function sendEmail(opts) {
const rsp = await fetch('https://api.postmarkapp.com/email', {
Expand All @@ -13,7 +13,7 @@ export async function sendEmail(opts) {
From: 'noreply@dag.house',
To: opts.to,
Subject: 'Hello',
HtmlBody: `<strong>Hello</strong> <br/><hr/> <code> ${opts.ucan}</code><hr/>`,
HtmlBody: `<strong>Hello</strong><br/>Click <a href="${opts.url}"> here </a><hr/>`,
MessageStream: 'outbound',
}),
})
Expand Down
8 changes: 6 additions & 2 deletions packages/access-api/test/helpers/setup.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,9 +47,13 @@ export async function send(ucan) {
})
}

export function connection() {
/**
* @param {import("@ucanto/interface").SigningAuthority<237> } id
*/
export function connection(id) {
return w3connection({
id: serviceAuthority,
id,
url: new URL('http://localhost:8787'),
fetch: mf.dispatchFetch.bind(mf),
})
}
Loading

0 comments on commit 305b2d3

Please sign in to comment.